题目来自杭电http://acm.hdu.edu.cn/showproblem.php?pid=1002
A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 262063 Accepted Submission(s): 50723
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
代码
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[5000];
char b[5000];
char c[5000];
int n;
int i;
int j;
int flag;
int len_a;
int len_b;
int len_c;
int temp_a;
int temp_b;
cin >> n;
i = 1;
while(!(i > n))
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
j = 0;
cin >> a;
cin >> b;
len_a = strlen(a);
len_b = strlen(b);
len_a--;
len_b--;
flag = 0;
while(1)
{
temp_a = 0;
temp_b = 0;
if(len_a > 0 || len_a == 0)
temp_a = a[len_a] - '0';
if(len_b > 0 || len_b == 0)
temp_b = b[len_b] - '0';
if(len_a < 0 && len_b < 0 && flag == 0)
break;
len_a--;
len_b--;
temp_a += temp_b;
if(flag)
temp_a += 1;
if(temp_a > 9)
{
flag = 1;
temp_a -= 10;
c[j++] = temp_a + '0';
continue;
}
c[j++] = temp_a + '0';
flag = 0;
}
c[j] = '\0';
cout << "Case " << i << ":" << endl;
cout << a << " + " << b << " = ";
len_c =strlen(c);
len_c--;
while(!(c[len_c] - '0') && !(len_c < 0))
len_c--;
if(len_c < 0)
cout << 0;
else
{
while(!(len_c < 0))
{
cout << c[len_c];
len_c--;
}
}
if(i == n)
cout << endl;
if(i != n)
cout << endl << endl;
i++;
}
return 0;
}
总结:题目本身并不难理解,大数相加问题,只是可能会忽略一些特殊样例,还有一些格式要求,毕竟WA了好多次
格式要求:最后一个输出只有一个换行,其余是两个,还有中间输出空格的问题,这个问题并不大
特殊样例:当你觉得自己的程序跑的没问题而又不知道哪里错了的时候,可以试试这几个样例
123 987
0001 0000001
99900 00999