hdoj1002

A - A + B Problem II

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

InputThe 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. 
OutputFor 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
这道题一开始的思路是直接用字符数组去处理,做到一半发现实在太麻烦了,百度到他们把他放在整形数组里去处理好理解且方便.
且此题有BUG,我的程序输入1 9和1 99999999999这类数时候答案总是0,但是依然AC了- -!(玄学改变命运),不过最后还是改了一下,使程序更完美,
把进位的变量进行判断TM=1输出TM,else continue;
下面是我的程序:
 1 #include<iostream>
 2 using namespace std;
 3 #include<string.h>
 4 #include<stdio.h>
 5 #include<stack>
 6 #include<string.h>
 7 #include<string>
 8 #include<algorithm>
 9 #include<queue>
10 int max(int a,int b)
11 {
12     return a>b?a:b;
13 }
14 int main()
15 {
16     char a1[1010],b1[1010];
17     int a[1010],b[1010],c[1010];
18     int t,i,j;
19     cin>>t;
20     for(int k=1;k<=t;k++)
21     {
22         memset(a1,0,sizeof(a1));
23         memset(b1,0,sizeof(b1));
24         memset(a,0,sizeof(a));
25         memset(b,0,sizeof(b));
26         memset(c,0,sizeof(c));
27         cin>>a1>>b1;
28         int lena,lenb;
29         lena=strlen(a1);
30         lenb=strlen(b1);
31         for(i=0,j=lena-1;i<lena;i++,j--)
32         {
33             a[j]=a1[i]-'0';
34         }
35         for(i=0,j=lenb-1;i<lenb;i++,j--)
36         {
37             b[j]=b1[i]-'0';
38         }
39         int TM=0;
40         if(lena>=lenb)
41         {
42             for(i=0;i<lena;i++)
43             {
44                 c[i]=(a[i]+b[i]+TM)%10;
45                 TM=(a[i]+b[i]+TM)/10;
46             }
47         }
48         else
49         {
50             for(i=0;i<lenb;i++)
51             {
52                 c[i]=(a[i]+b[i]+TM)%10;
53                 TM=(a[i]+b[i]+TM)/10;
54             }
55         }
56         int lenc;
57         lenc=max(lena,lenb);
58         cout<<"Case "<<k<<":"<<endl;
59         cout<<a1<<" + "<<b1<<" = ";
60         if(TM)
61             cout<<TM;
62         for(i=lenc-1;i>=0;i--)
63             cout<<c[i];
64         cout<<endl;
65         if(k!=t)
66             cout<<endl;
67     }
68     return 0;
69 }

 


posted @ 2017-07-20 11:12  小小超plus  阅读(481)  评论(0编辑  收藏  举报