A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 265006 Accepted Submission(s): 51289
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
Recommend
第一次写大数问题,其实算法还是很好理解的,模拟小学的加法,不过需要将其使用代码实现。
题意:a+b求和,不过a,b的位数最大可达1000位,需要使用字符串输入计算,需要注意输出格式,最后一行不空行。
附上代码:
1 #include <iostream> 2 using namespace std; 3 #include <string.h> 4 int main() 5 { 6 int n,i,j=1,p,n1,n2; 7 char a[1000],b[1000],c[1001]; 8 cin>>n; 9 while(n--) 10 { 11 p=0; 12 cin>>a>>b; 13 cout<<"Case "<<j<<":"<<endl; 14 cout<<a<<" + "<<b<<" = "; 15 n1=strlen(a)-1; 16 n2=strlen(b)-1; 17 for(i=0; n1>=0||n2>=0; i++,n1--,n2--) 18 { 19 if(n1>=0&&n2>=0) c[i]=a[n1]+b[n2]-'0'+p; 20 if(n1>=0&&n2<0) c[i]=a[n1]+p; 21 if(n2>=0&&n1<0) c[i]=b[n2]+p; 22 p=0; 23 if(c[i]>'9') 24 { 25 c[i]-=10; 26 p=1; 27 } 28 } 29 if(p==1) cout<<1; 30 while(i--) 31 cout<<c[i]; 32 j++; 33 if(n!=0) 34 cout<<endl<<endl; 35 else 36 cout<<endl; 37 } 38 return 0; 39 }