7 solutions

  • 0
    @ 2022-8-6 22:21:05

    这是一道高精度问题,涉及高位加减法的时候,简单的相加数据会爆掉,所以我们用数组去模拟一位一位的加减法!

    #include <bits/stdc++.h>
    
    //高精度
    
    using namespace std;
    
    const int maxn = 505;
    int a[maxn], b[maxn], c[maxn];
    
    int main(void) {
        string aa, bb;
        cin >> aa >> bb;
    
        if (aa.size() < bb.size()) {
            swap(aa, bb);
        }
        int k = aa.size() - bb.size();
    
        for (int i = 0; i < aa.size(); i++) {
            if (i < k) {
                a[i] = aa[i] - '0';
                b[i] = 0;
            }
            else {
                a[i] = aa[i] - '0';
                b[i] = bb[i - k] - '0';
            }
        }
    
        int res = 0;
        for (int i = aa.size() - 1; i >= 0; i--) {
            c[i] = (a[i] + b[i] + res) % 10;
            res = (a[i] + b[i] + res) / 10;
        }
    
        if (res) cout << res;
        for (int i = 0; i < aa.size(); i++) {
            cout << c[i];
        }
    
        return 0;
    }
    

    Information

    ID
    66
    Time
    1000ms
    Memory
    256MiB
    Difficulty
    8
    Tags
    # Submissions
    772
    Accepted
    106
    Uploaded By