Given two non-negative integers
num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution:
We can split this process to:
1. multiply num1.charAt(i) and num2.charAt(j). Put the result in product[i + j + 1].
2. calculate carry and complete the multiplication.
3. output
Code:
public class Solution { public String multiply(String num1, String num2) { int n1 = num1.length(); int n2 = num2.length(); int[] product = new int[n1 + n2]; for (int i = n1 - 1; i >= 0; i--) { for (int j = n2 - 1; j >= 0; j--) { product[i + j + 1] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); } } int carry = 0; for (int i = n1 + n2 - 1; i >= 0; i--) { int sum = (product[i] + carry) % 10; carry = (product[i] + carry) / 10; product[i] = sum; } StringBuilder sb = new StringBuilder(); for (int num : product) { sb.append(num); } while (sb.length() != 0 && sb.charAt(0) == '0') { sb.deleteCharAt(0); } return sb.length() == 0 ? "0" : sb.toString(); } }