您的位置:首页 > 其它

杭电_ACM_A + B Problem II

2012-11-03 21:24 211 查看
[align=left]Problem Description[/align]
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.

[align=left]Input[/align]
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.

[align=left]Output[/align]

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.

[align=left]Sample Input[/align]

2
1 2
112233445566778899 998877665544332211


[align=left]Sample Output[/align]

Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110


View Code

#include <stdio.h>
#include <string>
#define MAX 1005
int main()
{
int T, a[MAX], b[MAX], c[MAX], i, j, k, carry;
char sa[MAX], sb[MAX];
scanf("%d", &T);
for (j = 1; j <= T; j++)
{
scanf("%s %s", sa, sb);
memset(a, 0, sizeof(a));
memset(b, 0, sizeof(b));
carry = 0;
//a[0] is the length of a, it's more convenient
a[0] = strlen(sa);
b[0] = strlen(sb);
//translate the char to number and inverse
for (i = 1; i <= a[0]; i++)
{
a[i] = sa[a[0] - i] - '0';
}
for (i = 1; i <= b[0]; i++)
{
b[i] = sb[b[0] - i] - '0';
}
//get the longer one for result
c[0] = a[0] > b[0] ? a[0] : b[0];
//add one by one and note the carry
for (i = 1; i <= c[0]; i++)
{
c[i] = (a[i] + b[i] + carry) % 10;
carry = (a[i] + b[i] + carry) / 10;
}
//if the last carry is not zero, you must add the one.
if (carry != 0)
{
c[0]++;
c[c[0]] = carry;
}
//formatted printing
printf("Case %d:\n", j);
for (k = a[0]; k >= 1; k--)
printf("%d", a[k]);
printf(" + ");
for (k = b[0]; k >= 1; k--)
printf("%d", b[k]);
printf(" = ");
for (k = c[0]; k >= 1; k--)
printf("%d", c[k]);
printf("\n");
if (j != T)
printf("\n");
}
return 0;
}


firstly, making your mind clearly.

secondly, in formatted printting, you should care about two lines or one line.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: