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
 1 #pragma warning(disable:4996)
 2 #include<map>
 3 #include<string>
 4 #include<cstdio>
 5 #include<bitset>
 6 #include<cstring>
 7 #include<iostream>
 8 #include<algorithm>
 9 using namespace std;
10 typedef long long ll;
11 
12 const int maxn = 1005;
13 
14 char s1[maxn], s2[maxn], ans[maxn];
15 
16 void sum(char *s1, char *s2) {
17     int len1 = strlen(s1);
18     int len2 = strlen(s2);
19     for (int i = 0; i < len1; i++) s1[i] -= '0';
20     for (int i = 0; i < len2; i++) s2[i] -= '0';
21     int mid1 = len1 >> 1;
22     int mid2 = len2 >> 1;
23     /*调换位置*/
24     for (int i = 0; i < mid1; i++) swap(s1[i], s1[len1 - i - 1]);
25     for (int i = 0; i < mid2; i++) swap(s2[i], s2[len2 - i - 1]);
26     int len3 = max(len1, len2);
27     int x = 0, y;
28     /*多考虑一位*/
29     for (int i = 0; i <= len3; i++) {
30         y = s1[i] + s2[i] + x;
31         ans[i] = y % 10;
32         x = y / 10;    
33     }
34 
35     while (len3 > 0 && ans[len3] == 0) len3--;
36     if (len3 == 0) { printf("%d\n", ans[0]); return; }
37     else {
38         for (int i = len3; i >= 0; i--) printf("%d", ans[i]);
39         printf("\n");
40         return;
41     }
42 }
43 
44 int main()
45 {
46     int T; cin >> T;
47     for (int i = 1; i <= T; i++) {
48         memset(s1, 0, sizeof(s1));
49         memset(s2, 0, sizeof(s2));
50         scanf("%s%s", s1, s2);
51         printf("Case %d:\n", i);
52         printf("%s + %s = ", s1, s2);
53         sum(s1, s2);
54         if (i != T) printf("\n");
55     }
56     return 0;
57 }

 

posted @ 2018-03-21 20:47  天之道,利而不害  阅读(167)  评论(0编辑  收藏  举报