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 Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
Author
Ignatius.L
AC code:
1
#include
<
iostream
>
2 using namespace std;
3 void add( char a[], char b[])
4 {
5 char sum[ 1010 ] = { ' ' };
6 int flg = 0 ;
7 int temp = 0 ;
8 int len_a = strlen(a);
9 int len_b = strlen(b);
10 int i = len_a;
11 int j = len_b;
12 for (;i > 0 ;i -- )
13 {
14 if (j > 0 )
15 {
16 temp = a[i - 1 ] + b[j - 1 ] + flg - 96 ;
17 j -- ;
18 }
19 else temp = a[i - 1 ] + flg - 48 ;
20 if (temp >= 10 )
21 {
22 flg = 1 ;
23 }
24 else flg = 0 ;
25 temp = temp % 10 ;
26 sum[i] = temp + 48 ;
27 }
28 if (flg == 1 )sum[ 0 ] = 49 ;
29 i = 0 ;
30 while (i <= len_a)
31 {
32 if (sum[i] != ' ' )cout << sum[i];
33 i ++ ;
34 }
35 cout << endl;
36 }
37 void main()
38 {
39 int N;
40 while (cin >> N )
41 {
42 for ( int i = 1 ;i <= N;i ++ )
43 {
44 char a[ 1000 ];
45 char b[ 1000 ];
46 cin >> a;
47 cin >> b;
48 int len_a = strlen(a);
49 int len_b = strlen(b);
50 cout << " Case " << i << " :\n " << a << " + " << b << " = " ;
51 if (len_a >= len_b)
52 {
53 add(a,b);
54 }
55 else add(b,a);
56 if (i != N)cout << endl;
57 }
58 }
2 using namespace std;
3 void add( char a[], char b[])
4 {
5 char sum[ 1010 ] = { ' ' };
6 int flg = 0 ;
7 int temp = 0 ;
8 int len_a = strlen(a);
9 int len_b = strlen(b);
10 int i = len_a;
11 int j = len_b;
12 for (;i > 0 ;i -- )
13 {
14 if (j > 0 )
15 {
16 temp = a[i - 1 ] + b[j - 1 ] + flg - 96 ;
17 j -- ;
18 }
19 else temp = a[i - 1 ] + flg - 48 ;
20 if (temp >= 10 )
21 {
22 flg = 1 ;
23 }
24 else flg = 0 ;
25 temp = temp % 10 ;
26 sum[i] = temp + 48 ;
27 }
28 if (flg == 1 )sum[ 0 ] = 49 ;
29 i = 0 ;
30 while (i <= len_a)
31 {
32 if (sum[i] != ' ' )cout << sum[i];
33 i ++ ;
34 }
35 cout << endl;
36 }
37 void main()
38 {
39 int N;
40 while (cin >> N )
41 {
42 for ( int i = 1 ;i <= N;i ++ )
43 {
44 char a[ 1000 ];
45 char b[ 1000 ];
46 cin >> a;
47 cin >> b;
48 int len_a = strlen(a);
49 int len_b = strlen(b);
50 cout << " Case " << i << " :\n " << a << " + " << b << " = " ;
51 if (len_a >= len_b)
52 {
53 add(a,b);
54 }
55 else add(b,a);
56 if (i != N)cout << endl;
57 }
58 }
59 }