算法之俩个大数相乘

具体实现如下:

public class LargeNumMultiply {
    public static void main(String[] agrs) {
        long timeStart = System.currentTimeMillis();
        System.out.println("result=" + getResult("99", "19"));
        System.out.println("result=" + getResult("99", "99"));
        System.out.println("result=" + getResult("123456789", "987654321"));
        System.out.println("result=" + getResult("12345678987654321", "98765432123456789"));
        System.out.println("time=" + (System.currentTimeMillis() - timeStart));

    }
    
    public static String getResult(String bigIntA, String bigIntB) {
        int maxLength = bigIntA.length() + bigIntB.length();
        int[] result = new int[maxLength];
        int[] aInts = new int[bigIntA.length()];
        int[] bInts = new int[bigIntB.length()];
        
        for(int i=0; i= 0; i--) {
            curr = bigIntA.length() + i;
            for(int j=bigIntA.length()-1; j>=0; j--) {
                z = bInts[i] * aInts[j] + result[curr]; // 乘积并加上上一次计算的进位
                x = z % 10; // 个位
                y = z / 10; // 十位
                result[curr] = x; // 计算存到数组c中
                result[curr -1]+= y; // curr - 表示前一位,这里是进位的意思
                curr--;
            }
        }
        
        int t = 0;
        for(; t

运行结果:

算法之俩个大数相乘_第1张图片
俩个大数相乘.png

你可能感兴趣的:(算法之俩个大数相乘)