A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 310717 Accepted Submission(s):
60078
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
Recommend
解题心得:
这是个大数问题,题意要求计算不超过1000位的两个数字相加,所以必须要用字符串存储两个数字。
我刚开始选择的是让他们从最低位开始相加,但是两个字符串需要考虑长度问题,写完后有发现很多问题。
忽略了进位问题,可能不止进一位,当99999+1时就需要进好几位。结果一遍一遍的改就是不对,下面的代码是错误的。
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int main() { int n; char a[1005],b[1005],ab[1005]; int c_a,c_b; int i1=0,i2=0,ii; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%s %s",a,b); printf("Case %d: ",i+1); c_a=strlen(a); c_b=strlen(b); if(c_a<c_b){ for(int j=c_a;j>=0;j--){ a[j+c_b-c_a+1]=a[j]; } for(int j=c_b-1;j>=0;j--){ b[j+1]=b[j]; } memset(a,'0',(c_b-c_a+1)*sizeof(char)); memset(ab,'0',c_b*sizeof(char)); for(int j=c_a+1;j>=0;j--){ ii=(int)(a[j]-48)+(int)(b[j]-48)+i2; i1=ii/10; i2=ii%10; ab[j]=(char)(i2+48); i2=i1; } ab[c_b+1]='