/** * 超级计算器——两个大数相乘 * * @author GaoHuanjie */ public class SuperCalculator { public static void main(String[] args) { String multiplier1 = "12"; String multiplier2 = "70"; // String multiplier1 = "13286754398172596"; // String multiplier2 = "2397567453241147"; System.out.println(multiplier1+"x" + multiplier2+"="+product(multiplier1, multiplier2)); } /** * 字符串顺序取反 */ private static String reverse(String str) { return new StringBuffer(str).reverse().toString(); } /** * 将char类型的数据转int类型 */ private static int covertInt(char str){ return Integer.parseInt(String.valueOf(str)); } public static String product(String multiplier1, String multiplier2) {//以12x70为例 char[] multiplierArray1 = reverse(multiplier1).toCharArray();// 高低位对调 {2,1} char[] multiplierArray2 = reverse(multiplier2).toCharArray();// 高低位对调 {0,7} int multiplierLength1 = multiplierArray1.length;// 2 int multiplierLength2 = multiplierArray2.length;// 2 int productSize = multiplierLength1 + multiplierLength2;//两个数的乘积的最大长度 4 int[] productArray = new int[productSize];//乘积数组 {0,0,0,0} for (int j = 0; j < multiplierLength2; j++) {// 对齐逐位相乘 {0,7} for (int i = 0; i < multiplierLength1; i++) {// {2,1} productArray[i + j] = productArray[i + j] + (covertInt(multiplierArray1[i])* covertInt(multiplierArray2[j])); } } //到此productArray元素为{0,14,7,0} for (int i = 0; i < productSize; i++) {// 进位处理 //i=0 i=1 i=2 i=3 int quotient = productArray[i] / 10;//商 0 1 0 0 productArray[i] = productArray[i] % 10;// 0 4 8 0 if (quotient > 0) { productArray[i + 1] = productArray[i + 1] + quotient; } } //到此productArray元素为 {0,4,8,0} int m = 0; for (m = productSize - 1; m >= 0;) {// 找到最高位 if (productArray[m] > 0) { break; } m--; } //至此m的值为 2 StringBuffer stringBuffer = new StringBuffer(); for (int n = 0; n <= m; n++) {// 由最高位開始打印乘积 stringBuffer.append(productArray[m - n]); } // 至此乘积为840 return stringBuffer.toString(); } }