1. 程式人生 > >SDNUOJ 1303 加法高精度

SDNUOJ 1303 加法高精度

Description
求A+B

Input
多組測試樣例。兩個正整數X,Y(0≤X,Y≤10^100)
Output
輸出結果
Sample Input
1 1
12345 54321
Sample Output
2
66666

開始沒看到要多組輸入樣例,鬱悶了一會兒…

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
using namespace std;

int main()
{
    char a[105] = {}, b[105] = {}, c[105] = {};
    while(cin >> a)
    {
        cin >> b;
        int lena = strlen(a);
        int lenb = strlen(b);
        ///確保 a 是較大(較長)的數字
        if(lena < lenb)
        {
            for(int i = 0; i < lenb; i++)
            {
                swap(a[i], b[i]);
            }
            swap(lena, lenb);
        }
        reverse(a, a+lena);
        reverse(b, b+lenb);
//    cout << a << '\n' << b << '\n';
        ///逢十所進
        int j = 0;
        int i;
        for(i = 0; i < lenb; i++)
        {
            c[i] = (a[i] + b [i] - '0' - '0' + j)%10 + '0';
            j = (a[i] + b[i] - '0' - '0' + j)/10;
        }
        for(int k = i; k < lena; k++)
        {
            ///照顧銜接處及末(反轉後)
            c[k] = (a[k] + j - '0' )%10 + '0';
            j = (a[k] + j - '0' )/10;
        }
        if(j != 0)
            cout << j;
        for(int m = lena - 1; m >= 0; m--)
            cout << c[m];
        cout << '\n';
    }
    return 0;
}