杭电OJ——1002

1002 A+B Problem II

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 Input2

1 2
112233445566778899 998877665544332211

Sample Output

Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

原题
这道题真的是虐我千百遍啊!!!
提交了好多次
在这里我介绍一下,做题过程中需要注意的点:
1)这道题的数据非常大,所以不能用一惯用的类型来存储数据,所以我用到了数组来存储数据;
2)注意输出格式:“+”和“=”两边都有空格,输出的结果中间有换行,但最后一组没有,否则会报错:Presentation Error;
3)注意从个位开始相加,要注意进位

源代码


#include<iostream>
#include<cstdio>
#include<string> 
using namespace::std;
int main()
{
 int T,num,sum[1010];
 string A,B;
 num=0;
 cin>>T;
 while(T--)
 {   
     int lA,lB,m,n,k,tmp;
     m=0;n=0;k=0;tmp=0;
     cin>>A>>B;
     lA=A.length();
     lB=B.length();
     lA=lA-1;
     lB=lB-1;
     while(lA>=0&&lB>=0)
     {
      m=A[lA]-'0';
      n=B[lB]-'0';
      sum[k++]=(tmp+m+n)%10;
      tmp=(tmp+m+n)/10; //十进制,进位 
      lA--;
      lB--;
  }
  if(lA>lB)
  {
   while(lA>=0)
   {
    m=A[lA]-'0';
    sum[k++]=(tmp+m)%10;  //不要忘记 tmp
    tmp=(tmp+m)/10;
    lA--;
   }
  }
  if(lB>lA)
  {
   while(lB>=0)
   {
    n=B[lB]-'0';
    sum[k++]=(tmp+n)%10;
    tmp=(tmp+n)/10;
    lB--;
   }
  }
  sum[k]=tmp;  //不要忘记 tmp
     cout<<"Case "<<++num<<":"<<endl;
     cout<<A<<" + "<<B<<" = ";
  if(sum[k]!=0)
      cout<<sum[k];
     for(int i=k-1;i>0;i--)
      cout<<sum[i];
     cout<<sum[0]<<endl;
  if(T!=0)
      cout<<endl;  
 }
 return 0;
}

暂时就这些,想到什么再来补充,欢迎大家指正

你可能感兴趣的:(刷题)