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
题目解析:
与HDOJ_1000不同,这里包含大整数加法。因此,不能按那个方法进行处理,这里采用了字符串进行大整数的加法。
代码如下:
-
#include <stdio.h>
-
#include <string.h>
-
-
#define MAXNUM 1004
-
-
//交换
-
void Swap(char *a, char *b)
-
{
-
char tmp = *a;
-
*a = *b;
-
*b = tmp;
-
}
-
//反转
-
void reserve(char *a, int len)
-
{
-
int i, j;
-
if(a == NULL || len == 0)
-
{
-
return;
-
}
-
-
i = 0;
-
j = len - 1;
-
while(i < j)
-
{
-
Swap(&a[i], &a[j]);
-
i++;
-
j--;
-
}
-
}
-
-
int main(int argc, char* argv[])
-
{
-
int t = 0;
-
char a[MAXNUM];
-
char b[MAXNUM];
-
int c[MAXNUM];
-
int i = 0, j = 1;
-
int count = 1;
-
int len_a, len_b, len_c;
-
-
scanf("%d", &t);
-
if(t <= 0 || t >= 21)
-
{
-
return 0;
-
}
-
for(j = 1; j <= t; j++)
-
{
-
memset(a, 0, sizeof(a));
-
memset(b, 0, sizeof(b));
-
memset(c, 0, sizeof(c));
-
-
scanf("%s %s", a, b);
-
-
printf("Case %d:\n", count++);
-
printf("%s + %s = ", a, b);
-
-
len_a = strlen(a);
-
len_b = strlen(b);
-
len_c = (len_a > len_b) ? len_a : len_b;
-
-
//反转a和b
-
reserve(a, len_a);
-
reserve(b, len_b);
-
-
//转为数字
-
for(i = 0; i < len_a; i++)
-
{
-
a[i] -= '0';
-
}
-
for(i = 0; i < len_b; i++)
-
{
-
b[i] -= '0';
-
}
-
-
//计算
-
for(i = 0; i < len_c; i++)
-
{
-
c[i] = c[i] + a[i] + b[i];
-
c[i + 1] += c[i] / 10;
-
c[i] %= 10;
-
}
-
-
//有进位
-
if(c[len_c] > 0)
-
{
-
len_c++;
-
}
-
-
//输出
-
for(i = len_c - 1; i >= 0; i--)
-
{
-
printf("%d",c[i]);
-
}
-
printf("\n");
-
if(j != t)
-
{
-
printf("\n");
-
}
-
}
-
return 0;
-
}
阅读(1099) | 评论(0) | 转发(0) |