java两个或多个超大数相加

public class BigDataAddUtils {
    public static String add(String... params) {
        int maxLeng = 0;
        // 获取最大长度
        for (String s : params) {
            if (s.length() > maxLeng)
                maxLeng = s.length();
        }

        StringBuffer result = new StringBuffer();
        // 进位 数
        int high = 0;
        // 将每个待加参数每一位相加 进位
        for (int i = 0; i < maxLeng; i++) {
            int charInt = 0;
            for (String s : params) {
                // 高位不够用0代替
                charInt += s.length() - 1 < i ? 0 : Integer.parseInt(s.charAt(s.length() - 1 - i) + "");
            }
            charInt += high;
            // 进位
            high = charInt / 10;
            // 当前位的值 为charInt 余数
            int remainder = charInt % 10;
            result.append(remainder);
        }
        // 最后一次进位
        if (high > 0) {
            result.append(high);
        }
        // 反转 输出结果
        return result.reverse().toString();
    }

    public static void main(String[] args) {
        
        String aa="100000";
        String bb="100";
        String cc="1";
        
        System.out.print(add(aa, bb, cc));
    }
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值