Multiply Strings
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note:
- The numbers can be arbitrarily large and are non-negative.
- Converting the input string to integer is NOT allowed.
- You should NOT use internal library such as BigInteger.
分析:
把结果放在一个数组里,用offset来移动起始位置。
1 public class Solution { 2 public String multiply(String num1, String num2) { 3 if (num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0) return ""; 4 int[] result = new int[num1.length() + num2.length()]; // maximum length 5 6 int offset = 0; 7 for (int i = num1.length() - 1; i >= 0; i--) { 8 int number1 = num1.charAt(i) - '0'; 9 int carry = 0; 10 for (int j = num2.length() - 1; j >= 0; j--) { 11 int number2 = num2.charAt(j) - '0'; 12 int value = number1 * number2 + result[(result.length - 1) - offset + j - (num2.length() - 1)] + carry; 13 carry = value / 10; 14 value = value % 10; 15 result[(result.length - 1) - offset + j - (num2.length() - 1)] = value; 16 } 17 result[(result.length - 1) - offset - 1 - (num2.length() - 1)] = carry; 18 offset++; 19 } 20 String str = ""; 21 boolean isBeginningZero = true; 22 for (int i = 0; i < result.length; i++) { 23 if (!(result[i] == 0 && isBeginningZero == true)) { 24 isBeginningZero = false; 25 str += result[i]; 26 } 27 } 28 return str == "" ? "0" : str; 29 } 30 }
方法二:
Start from right to left, perform multiplication on every pair of digits, and add them together. Let's draw the process! From the following draft, we can immediately conclude:
`num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]`
1 public class Solution { 2 public String multiply(String num1, String num2) { 3 int m = num1.length(), n = num2.length(); 4 int[] pos = new int[m + n]; 5 6 for (int i = m - 1; i >= 0; i--) { 7 for (int j = n - 1; j >= 0; j--) { 8 int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); 9 int p1 = i + j, p2 = i + j + 1; 10 int sum = mul + pos[p2]; 11 pos[p1] += sum / 10; 12 pos[p2] = sum % 10; 13 } 14 } 15 16 StringBuilder sb = new StringBuilder(); 17 for (int p : pos) { 18 if (!(sb.length() == 0 && p == 0)) { 19 sb.append(p); 20 } 21 } 22 return sb.length() == 0 ? "0" : sb.toString(); 23 } 24 }