大数乘法
代码如下(示例):
public static String bigMultiply(String num1, String num2) {
int[] a = new int[num1.length()];
int[] b = new int[num2.length()];
for (int i = 0; i < num1.length(); i++)
a[i] = num1.charAt(i) - '0';
for (int i = 0; i < num2.length(); i++)
b[i] = num2.charAt(i) - '0';
int[] result = new int[a.length + b.length];
//进位
int carry = 0;
for (int i = a.length - 1; i >= 0; i--) {
carry = 0;
for (int j = b.length - 1; j >= 0; j--) {
int temp = a[i] * b[j] + carry + result[i + j + 1];
result[i + j + 1] = temp % 10;
carry = temp / 10;
}
// 仍有进位
if (carry != 0)
//i对应的为结果中的第i+j+1位,当下面的数字到头时即j=0时
// i对应的为结果中的第i+1位,所以进位是第i位置
result[i] = carry;
}
StringBuilder ans = new StringBuilder();
for (int i = 0; i < result.length; i++) {
if (i == 0 && result[i] == 0)
continue;
ans.append(result[i]);
}
return ans.toString();
}
以上注意的是:比如两位数乘两位数,1010=100就是3位数,而9999就是4位数,所以result数组的长度要开成相乘两数长度的和,最后再去除开头多余的0即可。