1. 程式人生 > >Week 1 # A A + B Problem II

Week 1 # A A + B Problem II

res lines osi 可能 c代碼 turn contains inpu mean

原題描述:

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
第二次看到這個題目了,第一次是在杭電acm上,那時侯想了用數組,不過沒做出來。其實這個題目不算難,我直接定義了兩個個字符型數組用來存儲算數,定義一個整形數組存儲值。先判斷那個數組長度大.
兩個字符型數組從後面相加,存儲到整形數組上,如果值大於10再向前進1(不可能大於20)一直到短的那個數組為0的時候停止相加。直接把長的賦值到上面就可以了,記得進位!
用長的字符型數組長度判斷整形數組的長度。然後就可以輸出了。代碼復雜,但是淺顯易懂。
AC代碼:
 1 #include <iostream>
 2 #include <string.h>
 3 const int N=1000;
 4 using namespace std;
 5 int main()
 6 {
 7     int t,l,m,n,sum[N+1]={0};
 8     int g=1;
 9     char a[N],b[N];
10     cin>>t;
11     while(t--)
12     {
13         int i;
14         cin>>a>>b;
15         m=strlen(a);
16         n=strlen(b);
17         l=m>=n?m:n;
18         if(m<=N&&n<=N)
19         {
20         if(m>=n)
21         {
22             for(i=0;n>0;i++)
23             {
24                 sum[i]=sum[i]+(a[m-1]-‘0‘)+(b[n-1]-‘0‘);
25                 m--;
26                 n--;
27                 if(sum[i]>9)
28                 {
29                     sum[i]-=10;
30                     sum[i+1]++;
31                 }
32             }
33             for( ;m>0;i++,m--)
34             sum[i]=sum[i]+(a[m-1]-‘0‘);
35         }
36         else
37          {
38             for(i=0;m>0;i++)
39             {
40                 sum[i]=sum[i]+(a[m-1]-‘0‘)+(b[n-1]-‘0‘);
41                 m--;
42                 n--;
43                 if(sum[i]>9)
44                 {
45                     sum[i]-=10;
46                     sum[i+1]++;
47                 }
48             }
49             for( ;n>0;i++,n--)
50             sum[i]=sum[i]+(b[n-1]-‘0‘);
51         }
52         }
53         if(sum[i]==0)
54         i--;
55         cout<<"Case "<<g<<":"<<endl;
56         g++;
57         cout<<a<<" + "<<b<<" = ";
58          for( ;i>=0;i--)
59         cout<<sum[i];
60         for(i=0;i<=l;i++)
61         sum[i]=0;
62         if(t!=0)
63         cout<<endl<<endl;
64         else cout<<endl;
65     }
66     return 0;
67 }

Week 1 # A A + B Problem II