跳至正文

1 条题解

  • 0
    @ 2026-10-8 19:19:21

    【本题解由站长编写】

    大数加法,位数可达 1000。用字符串模拟竖式加法:从低位到高位遍历(两个字符串都倒着取),逐位相加并处理进位,越界位当 0,最后把结果反转输出。

    代码(C++17)

    #include <bits/stdc++.h>
    using namespace std;
    
    string addBig(const string &a, const string &b) {
        string res;
        int i = (int)a.size() - 1, j = (int)b.size() - 1, carry = 0;
        while (i >= 0 || j >= 0 || carry) {
            int s = carry;
            if (i >= 0) s += a[i--] - '0';
            if (j >= 0) s += b[j--] - '0';
            res.push_back(char('0' + s % 10));
            carry = s / 10;
        }
        while (res.size() > 1 && res.back() == '0') res.pop_back();
        reverse(res.begin(), res.end());
        return res;
    }
    
    int main() {
        string a, b;
        cin >> a >> b;
        cout << addBig(a, b) << endl;
        return 0;
    }
    
    • 1

    信息

    ID
    4166
    时间
    1000ms
    内存
    256MiB
    难度
    6
    标签
    递交数
    0
    已通过
    0
    上传者