大数乘法计算Java代码实现

public static void multiply(String s1, String s2) {
        int[][] a = new int[s1.length()][s2.length()];
        for (int i = 0; i < s1.length(); i++) {
            int t1 = Integer.parseInt(String.valueOf(s1.charAt(i)));
            for (int j = 0; j < s2.length(); j++) {
                int t2 = Integer.parseInt(String.valueOf(s2.charAt(j)));
                a[i][j] = t1 * t2;
            }
        }

        // 对角线相加
        int[] x = new int[s1.length() + s2.length() - 1];
        x[0] = a[0][0];
        x[x.length - 1] = a[s1.length() - 1][s2.length() - 1];
        int k=1;
        while (k<= s1.length() + s2.length() - 3) {// 对角线元素相加
            for (int i = 0; i <= Math.min(k, s1.length() - 1); i++) {
                for (int j = 0; j <= Math.min(k, s2.length() - 1); j++) {
                    if (i + j == k) {
                        x[k] += a[i][j];
                    }
                }
            }
            k++;
        }
        int c = 0;
//      System.out.println(Arrays.toString(x));
        // 处理进位问题
        for (int i = x.length - 1; i > 0; i--) {
            c = x[i] / 10;
            x[i - 1] += c;
            x[i] = x[i] % 10;
        }
        String res = new String();
        for (int i = 0; i < x.length; i++) {
            res = res + x[i];
        }
        System.out.println("乘法结果:" + res);
    }

你可能感兴趣的:(java)