大整数乘法算法

本文介绍了如何在编程中处理大整数乘法问题,通过模拟手工算法来解决,使用字符串存储大整数,避免使用long类型。文章详细展示了代码实现过程,包括进位、正负号处理以及具体计算步骤。
摘要由CSDN通过智能技术生成
刷笔试题的时候遇到了一个大整数乘法的问题,做法就是模拟手工算法,只要注意不能用long来存储,而要使用string。其中还有一些细节需要注意,例如进位,正负号等。
代码如下:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    while (in.hasNext()) {
        boolean s = true;
        String a = in.next();
        String b = in.next();
        if (a.charAt(0) == '-') {
            a = a.substring(1, a.length());
            s = !s;
        }
        if (b.charAt(0) == '-') {
            b = b.substring(1, b.length());
            s = !s;
        }

        String[] resList = new String[1000];
        for (int i = 0; i < 1000; i++) {
            resList[i] = "0";
        }
        int plus = 0;
        for (int i = b.length() - 1; i >= 0; i--) {
            String tRes = "";
            int now = Integer.parseInt(b.charAt(i) + "");
            for (int j = a.length() - 1; j >= 0; j--) {
                int now2 = Integer.parseInt(a.charAt(j) + "");
                int tmp = now * now2 + plus;
                if (tmp < 10) {
                    tRes = tRes + tmp;
                    plus = 0;
                } else {
                    tRes = tRes + (tmp % 10);
                    plus = tmp / 10;
                }
            }
            if (plus != 0) {
                tRes = tRes + plus;
                plus = 0;
            }
            boolean plus2 = false;
            for (int y = 0; y < tRes.length(); y++) {
                int tmp = Integer.parseInt(tRes.charAt(y) + "") + Integer.parseInt(resList[y + (b.length() - 1 - i)]) + (plus2 ? 1 : 0);
                if (tmp < 10) {
                    resList[y + (b.length() - 1 - i)] = tmp + "";
                    plus2 = false;
                } else {
                    resList[y + (b.length() - 1 - i)] = tmp - 10 + "";
                    plus2 = true;
                }
            }
            if (plus2) {
                resList[(b.length() - 1 - i) + tRes.length()] = Integer.parseInt(resList[(b.length() - 1 - i) + tRes.length()]) + "1";
                plus2 = false;
            }

        }
        boolean start = false;
        System.out.print(s ? "" : "-");
        for (int i = 999; i >= 0; i--) {
            if (!start && resList[i].equals("0")) {
                continue;
            }
            if (!start && !resList[i].equals("0")) {
                start = true;
                System.out.print(resList[i]);
            } else {
                System.out.print(resList[i]);
            }
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值