hduoj1002 A + B Problem II (大數相加 字串模擬)

可樂可樂嗎QAQ發表於2020-12-31

hduoj1002 A + B Problem II
Problem Description

I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.

Input

The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.

Output

For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line is the an equation “A + B = Sum”, Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.

Sample Input

2
1 2
112233445566778899 998877665544332211

Sample Output

Case 1:
1 + 2 = 3


Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

思路:字串模擬

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

string add_BigInt(string a,string b){
    int x = a.size(), y = b.size();
    x > y ? b.insert(b.begin(), x - y, '0'):a.insert(a.begin(),y - x,'0'); 
    int carry = 0;
    int n = a.size();
    string res = "";
    for(int i = n - 1; i >= 0; i--){
        int cur = (a[i] - '0') + (b[i] - '0') + carry;
        res  += '0' + cur % 10;
        carry = cur / 10;
    }
    if(carry) res += "1";
    while(res.back() == '0' && res.size() > 1)  res.pop_back();
    reverse(res.begin(),res.end());
    return res;
}

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

相關文章