算法之俩个大数相乘

2017-09-25  本文已影响13人  PeterHe888

具体实现如下:

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<bigIntA.length(); i++) {
            aInts[i] = bigIntA.charAt(i) - '0'; //bigIntA 字符转换为数字存到数组
        } 
        for(int i=0; i<bigIntB.length(); i++) {
            bInts[i] = bigIntB.charAt(i) - '0'; //bigIntB 字符转换为数字存到数组
        }
        
        int curr; // 记录当前正在计算的位置,倒序
        int x, y, z; // 记录个位,十位
        
        for(int i=bigIntB.length() -1; 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<maxLength; t++) {
            if(result[t] != 0)
                break; // 最前面的0都不输出
        }
        StringBuilder builder = new StringBuilder();
        if(t == maxLength) {
            builder.append('0');
        } else {
            for(int i = t; i< maxLength; i++) {
                builder.append(result[i]);
            }
        }
        return builder.toString();
    }
}

运行结果:

俩个大数相乘.png
上一篇 下一篇

猜你喜欢

热点阅读