您的位置:首页 > 其它

杭电acm刷题记录ID1002

2017-10-14 21:21 344 查看
[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.

 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
这个问题最蛋疼的地方就是可用的基本数据类型并不能满足题意。幸运的是,我在c课本里见过类似的题目,题目还提示可以用数组保存变量,于是思路就来了。题目说数字长度不会超过1000...1000很小吗,说得那么轻松。。。如果用数组的每一个元素装每个数的一位,一个数就要占掉1kb的内存。。。但也管不了那么多,就这样吧。我写了一个read函数来读取数字。因为加法运算要求低位对齐,我在读完后将整个数翻转,使低位放在高位前。这样两个加数的各位都是数组0号元素,这样就对齐了。然后在最后一位上写入66表示数字结束。这样最后打印输出时不会输出多余的零。add函数实现两个数相加。c存入上一位的进位。最后结果覆盖第一个加数。一堆条件控制,乱七八糟,不谈了。。。print将数字按正常顺序输出。
有一个很神奇的坑点就是一开始测试结果是presentation error。经过各种实验,最终断定错误是,最后输多了一行空行。。。
不多数了,上答案:
#include <stdio.h>
#include <stdlib.h>
void read(char* p)
{
short n = 0,i;
char c;
while (scanf("%c",&c) != EOF && c != ' ' && c != 10)
{
p
= c - '0';
n++;
}
for(i = 0; i <= n/2 -1; i++)
{
c = p[i];
p[i] = p[n - 1 - i];
p[n - 1 - i] = c;
}
p
= 66;
}
void add(char* p1, char* p2)
{
char c=0;
char f=0;
int i;
for(i = 0; i < 1000; i++)
{
if(p1[i] == 66) f += 1;
if(p2[i] == 66) f += 2;
if(f == 3)
{
if(c) p1[i]=c;
if(p1[i]) i++;
p1[i] = 66;
break;
}
else
{
p1[i] = (f==2?0:p2[i]) + (f==1?0:p1[i]) + c;
c = p1[i] / 10;
p1[i] %= 10;
}
}
}
void print(char* p)
{
int i=0;
while (p[i] != 66) i++;
for(i -= 1; i >= 0; i--)
{
putchar(p[i] + '0');
}
}
int main()
{
char** num;
int n,i;
scanf("%d",&n);
getchar();
num = calloc(sizeof(char*),n*2);
for(i = 0; i < n*2; i++)
{
num[i] = calloc(sizeof(char),1000);
read(num[i]);
}
for(i = 0; i < n; i++)
{
printf("Case %d:\n",i+1);
print(num[i*2]);
printf(" + ");
print(num[i*2+1]);
printf(" = ");
add(num[i*2],num[i*2+1]);
print(num[i*2]);
printf("\n");
if(i!=n-1)printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: