415. Add Strings

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
Given two non-negative integers 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.
也就是给定两个字符串形式的数字,进行相加, 然后返回一个字符串。
不允许直接使用字符串转换成数字的内置方法。

2,题目思路
一开始觉得直接用ASCII和字符的对应关系直接进行转换相加,虽然可以实现两个数的相加,但是当num1太大时(num的长度可能在5100左右,过大)int或者long或者其他形式的数字都无法存储。
因此不能进行数值形式的相加,而是需要进行字符串的按位处理。、
每次处理一位,然后对所得到的进位进行记录,进行一位一位的相加。

3,程序源码

class Solution {
public:
    string addStrings(string num1, string num2) {
        long len1 = num1.size()-1,len2 = num2.size()-1;
        vector<string> resVector;
        string res;
        int carry = 0;//进位的表示


        while(len1>=0||len2>=0||carry>0)
        {
            int tempSum = 0;
            int tempRes = 0;
            if(len1>=0)
            {
                tempSum += num1[len1]-'0';//得到数字(int型)
                len1--;
            }
            if(len2>=0)
            {
                tempSum +=num2[len2]-'0';
                len2--;

            }
            tempSum += carry;//根据上一次的进位更新
            carry = tempSum/10;//计算新的进位,因为两个数的加和很可能大于0;
            tempRes = tempSum%10;//个位作为结果位
            res += to_string(tempRes);
        }
        reverse(res.begin(),res.end());
        return res;

    }
};

因为对于num1和num2都是从字符串的末尾开始进行操作的,也就是最小的部分,而在最后的字符串相加时都是在所得字符串末尾相加,因此得到的结果还需要进行reverse操作得到正确的字符串。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值