[LeetCode]--415. Add Strings

本文介绍了一种不使用内置大数库或直接转换为整数的方法来实现两个非负数字符串的相加操作。通过两种不同的实现方式,展示了如何逐位计算并处理进位的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.

public String addStrings(String num1, String num2) {
        char[] num1s = num1.toCharArray();
        char[] num2s = num2.toCharArray();
        int flag = 0, temp = 0, len1 = num1s.length - 1, len2 = num2s.length - 1;
        String result = "";
        int i = len1, j = len2;
        for (; i >= 0 && j >= 0; i--, j--) {
            temp = num1s[i] - '0' + num2s[j] - '0' + flag;
            if (temp > 9) {
                flag = 1;
                temp = temp % 10;
            } else
                flag = 0;
            result = temp + result;
        }
        while (i >= 0) {
            temp = num1s[i] - '0' + flag;
            if (temp > 9) {
                flag = 1;
                temp = temp % 10;
            } else
                flag = 0;
            result = temp + result;
            i--;
        }
        while (j >= 0) {
            temp = num2s[j] - '0' + flag;
            if (temp > 9) {
                flag = 1;
                temp = temp % 10;
            } else
                flag = 0;
            result = temp + result;
            j--;
        }
        if (flag == 1)
            result = flag + result;
        return result;
    }

看别人简便的写法,只是语言结构上简便。

public String addStrings(String num1, String num2) {
        StringBuffer sb = new StringBuffer();
        int l1 = num1.length();
        int l2 = num2.length();
        char[] c1 = num1.toCharArray();
        char[] c2 = num2.toCharArray();
        int carry = 0;
        for (int i = 0; i < l1 || i < l2; i++) {
            int a1 = i < l1 ? c1[l1 - 1 - i] - 48 : 0;
            int a2 = i < l2 ? c2[l2 - 1 - i] - 48 : 0;
            int ans = a1 + a2 + carry;
            sb.append(ans % 10);
            carry = ans / 10;
        }
        if (carry == 1) {
            sb.append("1");
        }
        return sb.reverse().toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值