首页 > 代码库 > 大数相加

大数相加

 

 

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char a[1100],b[1100];
    int t,lena,lenb,k,y,i,j;
    cin>>t;
    for (int m=1;m<=t;m++)
    {
        int c[1200]={0};
        cout << "Case " << m << ":" << endl;
        cin>>a>>b;
        k=0;
        lena=strlen(a);
        lenb=strlen(b);

        cout << a << " + " << b << " = " ;
        for (i=lena-1,j=lenb-1;i>=0&&j>=0;i--,j--)
        {
            y=a[i]-‘0‘+b[j]-‘0‘;
            if (y+c[k]>=10)
            {
                 c[k+1]++;
                 c[k]+=y-10;
            }
             else
                c[k]=c[k]+y;
                k++;
        }
      if (k<lena)
      {
          for (int x=i;x>=0;x--)
          {
               c[k]+=a[x]-‘0‘;
               k++;

          }
      }
      else if (k<lenb)
      {
          for (int x=j;x>=0;x--)
          {
               c[k]+=b[x]-‘0‘;
               k++;
          }
      }
      else if (c[k]!=0)
         k++;
      for (int z=k-1;z>=0;z--)
           cout << c[z] ;
           cout << endl;
      if (m!=t)
            cout << endl ;

    }
    return 0;
}

 

大数相加