43. Multiply Strings
the resut of num1[i]*num2[j] is located in result[i+j+1]; if >=10, carry to result[i+j];
class Solution {
public String multiply(String num1, String num2) {
int[] result = new int[num1.length()+num2.length()];
//multiply from end to begin
//the resut of num1[i]*num2[j] is located in result[i+j+1]; if >=10, carry to result[i+j];
for(int i = num1.length()-1; i>=0; i--){
for (int j= num2.length()-1; j>=0; j--){
int multi = (num1.charAt(i)-'0')*(num2.charAt(j)-'0') + result[i+j+1];
result[i+j+1] = multi%10;
result[i+j] = result[i+j] + multi/10;
}
}
// result[0]=result[0]+carry;
StringBuilder sb = new StringBuilder();
for (int i= 0; i<result.length;i++){
// remember the if condition
if (!(result[i]==0 && sb.length() == 0)) sb.append(result[i]);
}
return sb.length() == 0 ? "0" : sb.toString();
}
}
Last updated
Was this helpful?