大数相加

一:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm> 
using namespace std;
int compare(string str1,string str2)
{
    if(str1.length()>str2.length()) return 1;
    else if(str1.length()<str2.length())  return -1;
    else return str1.compare(str2);
}
string xj(string s1,string s2)
{
    string s;
    int len1=s1.length();
    int len2=s2.length();
    if(len1<len2){
        for(int i=1;i<=len2-len1;i++)
          s1="0"+s1;
    }
    else{
        for(int i=1;i<=len1-len2;i++)
          s2="0"+s2; 
    }
    len1=s1.length();
    int x=0,t;
    for(int i=len1-1;i>=0;i--){
        t=s1[i]-'0'+s2[i]-'0'+x;
        x=t/10;
        t%=10;
        s=char(t+'0')+s;
    }
    if(x!=0)
      s=char(x+'0')+s;
    return s;
}
int main()
{
    int n,i;
    cin>>n;
    for(i=0;i<n;i++)
    {
    string s1,s2;
    cin>>s1>>s2;
    cout<<"Case "<<i+1<<":"<<endl;
    cout<<s1<<" + "<<s2<<" = "<<xj(s1,s2)<<endl;
    if(i!=n-1)
        printf("\n");
    } 
    return 0;
}

二:

#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
const int maxn = 1000+10;
int main(void)
{
    int n[maxn],m[maxn],c[maxn];
    char a[maxn],b[maxn];
    int s1,s2,x,s3;
    int i,j,k,g,t;
    scanf("%d",&t);
    for(i=0;i<t;i++)
    {
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        memset(c,0,sizeof(c));
        memset(n,0,sizeof(n));
        memset(m,0,sizeof(m));
        cin>>a>>b;
        printf("Case %d:\n",i+1);
        s1=strlen(a);
        s2=strlen(b);
        for(j=0;j<s1;j++)
           n[s1-j]=a[j]-'0';
        for(k=0;k<s2;k++)
           m[s2-k]=b[k]-'0';
        s3=1;
        x=0;
        while(s3<=s1||s3<=s2)
        {
             c[s3]=n[s3]+m[s3]+x;
             x=c[s3]/10;
             c[s3]%=10;
             s3++;
        }
        c[s3]=x;
        while(c[s3]==0)
        {
            s3--;
        }
        cout<<a;
        printf(" + ");
        cout<<b;
        printf(" = ");
        for(g=s3;g>=1;g--)
        {
            printf("%d",c[g]);
        }
        printf("\n");
        if(i!=t-1)
            printf("\n"); 
    } 
    return 0;
} 

 

posted @ 2019-04-11 16:14  蓉~  阅读(215)  评论(0编辑  收藏  举报