hdu 1002 a + b problem ii

A + B Problem II

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 257918 Accepted Submission(s): 49865

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

1
2
3
2
1 2
112233445566778899 998877665544332211

Sample Output

1
2
3
4
5
Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

Idea

原题传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1002
新手必做题,简单的高精度加法,写了两个代码都AC了,第一个快些,第二个好理解些

Code1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

#include <stdlib.h>
#include <string.h>
#define MAX 1005

int (void)
{
int n, i = 1, n1, n2, k, j, p, q, x, m;
char a[MAX], b[MAX], c[MAX];


//freopen("output.txt","w", stdout);
scanf("%d", &n);
while(n)
{
scanf("%s %s", a, b);
printf("Case %d:n%s + %s = ", i, a, b);
n1 = strlen(a) - 1;
n2 = strlen(b) - 1;
k = x = 0;
while( n1 >= 0 || n2 >= 0)
{
p = n1 >= 0 ? a[n1--] - '0' : 0;
q = n2 >= 0 ? b[n2--] - '0' : 0;
m = p + q + x;
x = m / 10;
m = m % 10;
c[k++] = m + '0';
}
for(j = k - 1; j >=0; j--)
printf("%c", c[j]);
i++;
if(n != 1) printf("nn");
else printf("n");
n--;
}
return 0;
}

Code2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

#include <stdlib.h>
#include <string.h>
#define MAX 1015

void Add(char *a, char *b, char *c);
int (void)
{
int n;
int i;
char s1[MAX], s2[MAX], s3[MAX];


//freopen("output.txt","w", stdout);
scanf("%d", &n);
//while(getchar() != 'n') continue;
for(i = 1; i <= n; i++) { scanf("%s %s", s1, s2); Add(s1, s2, s3); printf("Case %d:n%s + %s = %s", i, s1, s2, s3); if(i == n) printf("n"); else printf("nn"); } return 0; } void Add(char *a, char *b, char *c) { int i = strlen(a) - 1, j = strlen(b) - 1, k = 0; int x = 0, m = 0; char t[MAX]; int p, q; while( i >= 0 || j >= 0)
{
p = i >= 0 ? a[i--] - '0' : 0;
q = j >= 0 ? b[j--] - '0' : 0;
m = p + q + x;
x = m / 10;
m = m % 10;
t[k++] = m + '0';
}
for(i = 0; i < k; i++)
c[i] = t[k - i - 1];
c[k] = '