1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| class Solution { public String multiply(String num1, String num2) { if (num1.equals("0") || num2.equals("0")) { return "0"; }
int[] nums = new int[num1.length() + num2.length()]; for (int i = num2.length() - 1; i >= 0; i--) { for (int j = num1.length() - 1; j >= 0; j--) { int x = num2.charAt(i) - '0'; int y = num1.charAt(j) - '0'; int product = nums[i + j + 1] + x * y; int carry = product / 10; int num = product % 10;
nums[i + j + 1] = num; nums[i + j] += carry; } }
StringBuilder sb = new StringBuilder(); for (int i = 0; i < nums.length; i++) { if (i == 0 && nums[0] == 0) { continue; } sb.append(nums[i]); } return sb.toString(); } }
|