愿你坚持不懈,努力进步,进阶成自己理想的人

—— 2017.09, 写给3年后的自己

杭电OJ1002 - 大数字A+B问题

AC代码:

#include <iostream>
#include <algorithm>
using namespace std;

string add(string a, string b) {
    long lenA = a.length();
    long lenB = b.length();
    long maxLen = lenA > lenB ? lenA : lenB;
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    
    int *result = new int[maxLen+1];
    for(long i=0; i<maxLen+1; i++) result[i]=0;
    for(long i=0; i<maxLen; i++) {
        int curA = i<lenA ? a[i]-'0' : 0;
        int curB = i<lenB ? b[i]-'0' : 0;
        if(result[i]+curA+curB>=10) {
            result[i] += curA+curB-10;
            result[i+1]++;
        } else {
            result[i] += curA+curB;
        }
    }
    string sum="";
    for(long i=maxLen; i>=0; i--) {
        if(i!=maxLen || result[maxLen] !=0) {
            sum.append(1, result[i]+'0');
        }
    }
    return sum;
}

int main() {
    int cases, i;
    for(cin>>cases, i=1; i<=cases; i++) {
        string a,b;
        cin >> a >> b;
        cout << "Case " << i << ":" << endl;
        cout << a << " + " << b << " = " << add(a, b) << endl;
        if(i!=cases) cout << endl;
    }
}