**
A + B Problem II
**
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 549355 Accepted Submission(s): 104809
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
Author
Ignatius.L
解题思路
题目要求1000位数字的运算,显然即使是longlong也无法满足要求。因此使用char字符组进行逐位的运算。自己写的代码一直无法通过,这里的AC代码来自用户houzena
略有改动。添加了代码注释。
AC
#include<stdio.h>
#include<string.h>
void Bignum_add(char* s1, char* s2, char* s)
{
int i, j, a, l1, l2, L, t;
l1 = strlen(s1);
l2 = strlen(s2);//字符串长度
s[0] = '0';
a = 0;
if (l1 > l2) L = l1;
else L = l2;//L为两串长度最大值
s[L + 1] = '\0';//尾部赋值
for (i = L; l1 > 0 && l2 > 0; i--)//从尾部开始比较
{
a = (s1[--l1] - '0') + (s2[--l2] - '0') + a / 10;//注意0与‘0’区别
s[i] = a % 10 + '0';//数字转字符
}
while (l1) {
a = (s1[--l1] - '0') + a / 10;
s[i--] = a % 10 + '0';//若l1还有剩余,赋值给s
}
while (l2) {
a = (s2[--l2] - '0') + a / 10;
s[i--] = a % 10 + '0';//若l2还有剩余,赋值给s
}
s[i] = a / 10 + '0';//头部进位
t = 0;
while (s[t] == '0' && t < L) t++;//头部‘0’计数
strcpy(s, s + t);//去头部的‘0’。原理为对头部‘0’数量进行计数,储存为t,利用strcpy进行后移。例如将‘00001’改为‘1’
}
int main()
{
int T, d = 1;
char s[1005], s1[1005], s2[1005];//上限改为1005防止溢出
scanf("%d", &T);//读入
while (T--)//进行T次循环
{
scanf("%s%s", s1, s2);//字符串读入
Bignum_add(s1, s2, s);//相加
printf("Case %d:\n", d++);
printf("%s + %s = %s\n", s1, s2, s);//使用printf进行输出
if (T != 0) printf("\n");//还有需要输出的内容,换行
}
return 0;
}