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.
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
public class Solution {
public String multiply(String num1, String num2) {
if (num1 == null || num2 == null) {
return null;
}
int m = num1.length(), n = num2.length();
int[] sums = new int[m + n];

for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >=0; j--) {
int left = i + j, right = i + j + 1;
int sum = (num1.charAt(i) - '0') * (num2.charAt(j) - '0') + sums[right];
sums[right] = sum % 10;
sums[left] += sum / 10;
}
}

StringBuilder res = new StringBuilder();
for (int i = 0; i < sums.length; i++) {
if (!(res.length() == 0 && sums[i] == 0)) {
res.append(sums[i]);
}
}
return res.length() == 0 ? "0" : res.toString();
}
}