题解 | 大数加法

大数加法

https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475

class Solution {
public:
    string solve(string s, string t) {
        int n1 = s.size();
        int n2 = t.size();
        if(n1<n2)
            s = std::string(n2-n1, '0') + s;
        else if(n1>n2)
            t = std::string(n1-n2, '0') + t;

        int jinwei = 0;
        int n = max(n1, n2);
        int curr = 0;
        string res = "";
        for(int i=n-1; i>=0; i--){
            curr = s[i]-'0' + t[i]-'0' + jinwei;
            jinwei = curr / 10;
            curr %= 10;
            res = char(curr+'0') + res;
        }

        if(jinwei)
            res = char(jinwei+'0') + res;

        return res;
    }
};

为了能够更简单地相加,首先可以对齐二者长度,短的那个前面补‘0’即可。

全部评论

相关推荐

10-17 23:18
已编辑
西北农林科技大学 Web前端
独行m:给25可以试试,但他只能给12,那就是纯纯的事精
秋招,不懂就问
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务