SDNU 1303 高精度(A+B)

Description

求A+B

Input
多組測試樣例。兩個正整數X,Y(0≤X,Y≤10^100)

Output
輸出結果
Sample Input

1 1
12345 54321

Sample Output

2
66666

思路: 先用字符數組存起來,在將其轉化爲整形數組,當兩個數相加之和大於等於10時,向前進一位,然後再對自己取餘,和加法的打草的計算方法一樣。

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string m,n;
    while (cin >> m >> n)
    {
        int p,a[1005],b[1005];
        int i,t,x,y,len,j=0,q;
        for(t=0; t<1005; t++)
        {
            a[t]=0;
            b[t]=0;
        }
        for(i=n.size()-1; i>=0; i--)
            a[j++]=n[i]-'0';
        j=0;
        for(i=m.size()-1; i>=0; i--)
            b[j++]=m[i]-'0';
        len=max(n.size(),m.size());
        for(i=0; i<len; i++)
        {
            a[i]+=b[i];
            a[i+1]+=a[i]/10;
            a[i]%=10;
        }
        for(i=1004; i>=0; i--)
        {
            if(a[i]!=0)
            {
                q=i;
                break;
            }
        }
        for(i=q; i>=0; i--)
            cout<<a[i];
        cout<<endl;
    }
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章