欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

两个大数字乘法

程序员文章站 2022-06-07 22:48:00
...
 /**
     * 默认最大长度50位,可以调节,或者动态判断都行
     */
    static String[] all = new String[50];

    public static void main(String[] args) {
        System.out.println(multiply(Long.MAX_VALUE, Long.MAX_VALUE));
        System.out.println(multiply1(Long.MAX_VALUE, Long.MAX_VALUE));

    }


    private static String multiply1(Long a, Long b) {
        char[] as = a.toString().toCharArray();
        char[] bs = b.toString().toCharArray();
        for (int p1=0,i = as.length-1; i > -1; i--,p1++) {
            for (int p2=p1,j = bs.length-1; j > -1; j--,p2++) {
                Integer num = Integer.parseInt(bs[j]+"") * Integer.parseInt(as[i]+"");
                int pos = p2;
                addNum(num % 10, pos);
                if (num > 10) {
                    addNum(num / 10, pos+1);
                }
            }
        }
        for(int x = all.length -1  ;x > -1;x--){
            if(all[x] != null){
                System.out.print(all[x]);
            }
        }
        return "";
    }

    private static void addNum(int num, int i) {
        if (all[i] == null) {
            all[i] = "0";
        }
        Integer s1 = Integer.parseInt(all[i]);
        s1 = s1 + num;
        if (s1 >= 10) {
            all[i] = String.valueOf(s1 - 10);
            addNum(s1 / 10, i + 1);
        } else {
            all[i] = String.valueOf(s1);
        }

    }

    /**
     * JDK 提供,可以看看优化
     * @param x
     * @param y
     * @return
     */
    private static String multiply(long x, long y) {
        BigDecimal a = new BigDecimal(x);
        BigDecimal b = new BigDecimal(y);
        return a.multiply(b).toString();
    }