题解 | #大数加法#

大数加法

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

时间复杂度:o(n)

空间复杂度:o(1)

class Solution {
  public:
    string solve(string s, string t) {
        // 特殊情况处理
        if (s.empty())
            return t;
        if (t.empty())
            return s;
        // 让s为较长的字符串
        if (s.length() < t.length())
            swap(s, t);
        // 进位
        int add = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            int temp = s[i] - '0' + add;
            int j = t.length() - (s.length() - i);

            if (j >= 0) {
                temp += t[j] - '0';
            }
            s[i] = temp % 10 + '0';
            add = temp / 10;
        }
        // 最后的进位
        if (add == 1)
            s = '1' + s;

        return s;
    }
};

刷题题解(c++) 文章被收录于专栏

算法题题解(c++)

全部评论

相关推荐

09-19 13:59
门头沟学院 Java
用微笑面对困难:Trae一下,如果真成了,他用了直接发字节起诉代码版权,,这个代码不商用是没问题的如果没成也是情理之中的。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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