Java大数乘法
大數(shù)乘法
代碼如下(示例):
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];//進(jìn)位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;}// 仍有進(jìn)位if (carry != 0)//i對應(yīng)的為結(jié)果中的第i+j+1位,當(dāng)下面的數(shù)字到頭時即j=0時// i對應(yīng)的為結(jié)果中的第i+1位,所以進(jìn)位是第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();}以上注意的是:比如兩位數(shù)乘兩位數(shù),1010=100就是3位數(shù),而9999就是4位數(shù),所以result數(shù)組的長度要開成相乘兩數(shù)長度的和,最后再去除開頭多余的0即可。
總結(jié)
- 上一篇: Select之多表查询
- 下一篇: java美元兑换,(Java实现) 美元