如字符串”21”和”34” 乘积,个位为4*1,十位为4*2+3*1,百位为2*3.
由于字符串中高位在前,低位在后,不符合我们计算乘积的顺序,因而我们将字符串逆序一下,然后按照乘法法则和进位的加法法则进行运算即可。
public class Solution {
public String multiply(String num1, String num2) {
num1 = new StringBuilder(num1).reverse().toString();
num2 = new StringBuilder(num2).reverse().toString();
// even 99 * 99 is < 10000, so maximaly 4 digits
int[] d = new int[num1.length() + num2.length()];
for (int i = 0; i < num1.length(); i++) {
int a = num1.charAt(i) - '0';
for (int j = 0; j < num2.length(); j++) {
int b = num2.charAt(j) - '0';
d[i + j] += a * b;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < d.length; i++) {
int digit = d[i] % 10;
int carry = d[i] / 10;
sb.insert(0, digit);
if (i < d.length - 1)
d[i + 1] += carry;
}
//trim starting zeros
while (sb.length() > 0 && sb.charAt(0) == '0') {
sb.deleteCharAt(0);
}
if(sb.length() == 0)
return "0";
return sb.toString();
}
}
若是能够使用BigInteger
public class Solution {
public String multiply(String num1, String num2) {
BigInteger temp1 = new BigInteger(num1);
BigInteger temp2 = new BigInteger(num2);
BigInteger result = temp1.multiply(temp2);
return result.toString();
}
}