Question:
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.
Thinking:
Simulate the process of multiplying.
Solution: (Record the result from low digits to high digits in array)
public String multiply(String num1, String num2) {
int l1 = num1.length(), l2 = num2.length();
int[] res = new int[l1+l2];
for (int i = l1-1; i >= 0; i--) {
for (int j = l2-1; j >= 0; j--){
int index = l1+l2-i-j-2;
res[index] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
res[index+1] += res[index] / 10;
res[index] = res[index] % 10;
}
}
StringBuilder fres = new StringBuilder();
for (int i = res.length-1; i >= 0; i--)
if (!(fres.length() == 0 && res[i] == 0)) fres.append(res[i]);
return fres.length() == 0? "0":fres.toString();
}
A little improvement which record the result from high to low digits in array:
public String multiply(String num1, String num2) {
int m = num1.length(), n = num2.length();
int[] pos = new int[m + n];
for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int p1 = i + j, p2 = i + j + 1;
int sum = mul + pos[p2];
pos[p1] += sum / 10;
pos[p2] = (sum) % 10;
}
}
StringBuilder sb = new StringBuilder();
for(int p : pos) if(!(sb.length() == 0 && p == 0)) sb.append(p);
return sb.length() == 0 ? "0" : sb.toString();
}
Reference: https://leetcode.com/discuss/71593/easiest-java-solution-with-graph-explanation