LeetCode 415. Add Strings 题解(C++)

LeetCode 415. Add Strings 题解(C++)


题目描述

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

补充

  • 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.

思路

  • 该算法为大数相加使用字符串string实现的问题。首先算出两个字符串的长度,并从两个字符串的最后一个字符开始循环,两个字符串对应位置的值相加,若有进制,则保存。若某一字符串的长度较长,需要将该字符串剩下的字符遍历完成,所以循环退出的条件是i>=0||j>=0;
  • 这里需要注意的是对字符串位置的操作,需要从两个给定字符串的最后一个位置开始,并且每次得到的结果应放置到结果字符串的首位置。
  • 对于数字和字符的相互转换,这里需要用到‘0’。

代码

class Solution 
{
public:
    string addStrings(string num1, string num2)
    {
        string num;
        int length1 = num1.length();
        int length2 = num2.length();
        int carry = 0;

        for (int i = length1 - 1, j = length2 - 1; i >= 0 || j >= 0; --i, --j)
        {
            int temp = 0;
            if (i >= 0)
            {
                temp += num1[i] - '0';
            }
            if (j >= 0)
            {
                temp += num2[j] - '0';
            }
            if (carry)
            {
                ++temp;
            }
            carry = temp / 10;
            temp = temp % 10;

            num = char(temp + '0') + num;
        }
        if (carry)
        {
            num = char(carry + '0') + num;
        }

        return num;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值