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
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char ads[105];
char s1[105],s2[105];
int additive(char* a,char* b)
{
    memset(ads,0,sizeof(ads));
    int len,len1,len2;
    int i;
    int ad[105];
    len1=strlen(a);
    len2=strlen(b);
    if(len1==len2)
    {
        len=len1;
    }
    else if(len1>len2)//短的数字位不足。将数字往后移,前面补“0”,便于计算
    {
        len=len1;
        for(i=len; i>=len-len2; i--)
        {
            b[i]=b[i-len+len2];
        }
        for(i=len-len2-1; i>=0; i--)
        {
            b[i]='0';
        }
    }
    else if(len1<len2)//短的数字位不足。将数字往后移,前面补“0”,便于计算
    {
        len=len2;
        for(i=len; i>=len-len1; i--)
        {
            a[i]=a[i-len+len1];
        }
        for(i=len-len1-1; i>=0; i--)
        {
            a[i]='0';
        }
    }
    int t=0;
    for(i=len-1; i>=0; i--)//进行计算
    {
        ad[i]=(a[i]-'0')+(b[i]-'0')+t;//把原本该有的数加上,再加上前一位需要进的“1”
        t=0;
        if(ad[i]>=10)
        {
            t++;
            ad[i]=ad[i]-10;
            ads[i]=ad[i]+'0';
        }
        else
        {
            ads[i]=ad[i]+'0';
        }
    }
    if(t==1)//如果位数已经变大,就将所有数往后移,再在最前面加一
    {
        for(i=len; i>=0; i--)
        {
            ads[i]=ads[i-1];
        }
        ads[0]='1';
    }
    return 0;
}
int main()
{
    while(scanf("%s",s1)!=EOF)
    {
        scanf("%s",s2);
        additive(s1,s2);
        cout<<ads<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/RootVount/p/10356761.html
今日推荐