HJ57 高精度整数加法

题目:

HJ57 高精度整数加法

题解:

1.逐位相加

按照传统加减法模式,从最后一位开始,逐位相加,逢十进一,传统方式从右往左相加,可以将数字翻转,变成从左往右按照数组遍历顺序相加,最后再将结果翻转。

java 复制代码
    public String getSum(String str1, String str2) {
        // 翻转
        List<Integer> list1 = revers(str1);
        List<Integer> list2 = revers(str2);

        int len1 = list1.size();
        int len2 = list2.size();

        int carryBit = 0;
        StringBuilder sb = new StringBuilder();
        int length = len1 > len2 ? len1 : len2;
        for (int i = 0; i < length; i++) {
            // 如果超出则取0
            int value1 = getValue(list1, i);
            int value2 = getValue(list2, i);
            int sum = value1 + value2 + carryBit;
            if (sum < 10) {
                sb.append(sum);
                carryBit = 0;
            } else {
                sb.append(sum % 10);
                carryBit = sum/10;
            }
        }

        // 如果最后还有进位,需要添加进位
        if (carryBit != 0) {
            sb.append(carryBit);
        }

        // 翻转结果
        sb.reverse();
        return sb.toString();
    }

    private int getValue(List<Integer> list, int index) {
        if (index >= list.size()) {
            return 0;
        }

        return list.get(index);
    }

    private List<Integer> revers(String str) {
        char[] chars = str.toCharArray();
        List<Integer> list = new ArrayList<>(chars.length);

        for (int i = chars.length - 1; i >= 0; i--) {
            list.add(chars[i] - '0');
        }

        return list;
    }

时间复杂度:O(n+m)

2.利用大整形类型BigInteger实现

java 复制代码
    public String getSum(String str1, String str2) {
        BigInteger bigInteger1 = new BigInteger(str1);
        BigInteger bigInteger2 = new BigInteger(str2);

        bigInteger1 = bigInteger1.add(bigInteger2);
        return bigInteger1.toString();
    }
相关推荐
不想编程小谭33 分钟前
力扣LeetCode: 2506 统计相似字符串对的数目
c++·算法·leetcode
水蓝烟雨1 小时前
[HOT 100] 2187. 完成旅途的最少时间
算法·hot 100
菜鸟一枚在这2 小时前
深度解析建造者模式:复杂对象构建的优雅之道
java·开发语言·算法
gyeolhada2 小时前
2025蓝桥杯JAVA编程题练习Day5
java·数据结构·算法·蓝桥杯
阿巴~阿巴~2 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
给bug两拳2 小时前
Day9 25/2/22 SAT
算法
_Itachi__3 小时前
LeetCode 热题 100 73. 矩阵置零
算法·leetcode·矩阵
夏末秋也凉3 小时前
力扣-贪心-376 摆动序列
算法·leetcode
Orange--Lin4 小时前
【用deepseek和chatgpt做算法竞赛】——还得DeepSeek来 -Minimum Cost Trees_5
人工智能·算法·chatgpt