A + B Problem II

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 32082    Accepted Submission(s): 5683


Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
 

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
 

Sample Input
2
1 2
112233445566778899 998877665544332211
 

Sample Output
Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

我的代码:

 

#include<iostream>
#include<string>
#define max 1000
using namespace std;
int min(int a,int b)
{
 if(a>b)return b;
 else return a;
}
int main()
{
 char a[max],b[max];
 int Ia[max],Ib[max],n,i,j,k,lena,lenb,z;

 cin>>n;
 for(i=0;i<n;i++)
 {
  k=0;
  z=0;
  cin>>a>>b;
  lena=strlen(a);
  lenb=strlen(b);
  cout<<"Case "<<i+1<<":"<<endl;
  for(j=0;j<lena;j++)cout<<a[j];
  cout<<" ";
  for(j=0;j<lena;j++)Ia[j]=a[lena-j-1]-48;//转换为整型数组 例如:input: 1234 转换为:4321这样就从个位数开始相加
  cout<<"+"<<" ";
  for(j=0;j<lenb;j++)cout<<b[j];
  cout<<" ";
  for(j=0;j<lenb;j++)Ib[j]=b[lenb-j-1]-48;
  cout<<"="<<" ";
  for(j=0;j<min(lena,lenb);j++)
   if(Ia[j]+Ib[j]+k>=10)//k为是否进位的标记
   {
    Ia[j]=(Ia[j]+Ib[j]+k)-10;
    k=1;
   }
   else
   {
    Ia[j]=Ia[j]+Ib[j]+k;
    k=0;
   }
  if(lena==min(lena,lenb)&&lena!=lenb)//Ib还有数,而Ia中已经没有数,此时只要再处理Ib中剩余的元素
  {
   for(j=lena;j<lenb;j++)
    if(Ib[j]+k>=10)
    {
     Ib[j]=Ib[j]+k-10;
     k=1;
    }
    else
    {
     Ib[j]=Ib[j]+k;
     k=0;
    }
    if(k==1)cout<<k;//做完了Ib中剩余的元素,K还是为1,则说明还有进位直接输出
    while(lenb-z-1>=lena)//将Ib中刚刚处理的剩余元素反向输出
    {
     cout<<Ib[lenb-z-1];
     z++;
    }
  }
       if(lenb==min(lena,lenb)&&lena!=lenb)
  {
   for(j=lenb;j<lena;j++)
    if(Ia[j]+k>=10)
    {
     Ia[j]=Ia[j]+k-10;
     k=1;
    }
    else
    {
     Ia[j]=Ia[j]+k;
     k=0;
    }
    if(k==1)cout<<k;
  }
  if(k==1&&lena==lenb)cout<<k;
    
  for(j=lena-1;j>=0;j--)
  {
   cout<<Ia[j];
   if(j==0&&i<n-1){cout<<endl;cout<<endl;}
  }
  if(i==n-1)cout<<endl;
 }
 return 0;
}
  

//这个题目,我做了很久才被AC,原因就是少了几个空格,还有输出的格式~通过这道题目,总结:ACM的题目要非常小心的阅读题目~否则后果很严重~呵呵

posted on 2009-07-10 22:15  Forgetting  阅读(1092)  评论(1)    收藏  举报