其实也就是大数的乘法
代码:
public String multiply(String num1, String num2) {
char[] ch1 = new StringBuilder(num1).reverse().toString().toCharArray();
char[] ch2 = new StringBuilder(num2).reverse().toString().toCharArray();
int[] result = new int[ch1.length + ch2.length];
for (int i = 0; i < ch1.length; i++){
int a = ch1[i] - '0';
for (int j = 0; j < ch2.length; j++){
int b = ch2[j] - '0';
result[i + j] += a * b;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i++){
int digit = result[i] % 10;
int carry = result[i] / 10;
if (i + 1 < result.length){
result[i + 1] += carry;
sb.insert(0, digit);
}else {
sb.insert(0, result[i]);
}
}
while (sb.length() > 0 && sb.charAt(0) == '0'){
sb.deleteCharAt(0);
}
return sb.length() > 0 ? sb.toString() : "0";
}