您的位置:首页 > 其它

大数的加法运算,杭电oj-1002

2015-03-15 12:10 399 查看
[align=left]原题地址:http://acm.hdu.edu.cn/showproblem.php?pid=1002[/align]
[align=left] [/align]
[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
【Sample Output】

Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
【AC代码】

#include<stdio.h>
#include<string.h>
#define max(a, b) a > b ? a:b

char a[1024];
char b[1024];
char c[1024];
int i;

void reverse(char *a)
{
int aa = strlen(a);
char t;
for(i=0; i<aa/2; i++)
{
t = a[i];
a[i] = a[aa-1-i];
a[aa-1-i] = t;
}
}
void add(char *a, char *b, char *c)
{
int cc = 0, aa = strlen(a), bb = strlen(b);
int len = max(aa, bb);
for(i=0; i<aa; i++)
{
a[i] = a[i]-'0';
}
for(i=0; i<bb; i++)
{
b[i] = b[i]-'0';
}
for(i=0; i<len; i++)
{
c[i] = (a[i]+b[i]+cc) % 10 + '0';
cc = (a[i]+b[i]+cc) / 10;
}
if(cc) c[i++] = cc + '0';
c[i] = '\0';
}
void print(char *c)
{
for(i = strlen(c)-1; i>=0; i--)
printf("%c", c[i]);
printf("\n");
}
main()
{
int n, j;
scanf("%d", &n);
for(j=1; j<=n; 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", j);
printf("%s + %s = ", a, b);
reverse(a), reverse(b);
add(a, b, c);
print(c);
if(j != n) printf("\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: