[leetcode] problem 43 – multiply strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example

No.1

Input: num1 = “2”, num2 = “3”

Output: “6”

No.2

Input: num1 = “123”, num2 = “456”

Output: “56088”

Note

  • The length of both num1 and num2 is < 110.
  • Both num1 and num2 contain only digits 0-9.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public String (String num1, String num2) {
int n = num1.length();
int m = num2.length();
int[] result = new int[m + n];
StringBuilder sb = new StringBuilder();

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

for (int val : result) {
if (sb.length() > 0 || val != 0)
sb.append(val);
}

return sb.length() > 0 ? sb.toString() : "0";
}