A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 261958 Accepted Submission(s): 50702
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(){ int T,cot=1; char a[1005],b[1005],c[1005],t[1005]; cin>>T; while(cot<=T){ cout<<"Case "<<cot<<": "; cin>>a>>b; cout<<a<<" + "<<b<<" = "; int la=strlen(a),lb=strlen(b); if(la<lb){//将a的长度变成大于b的长度的两个数 for(int i=0;i<la;i++) t[i]=a[i]; for(int i=0;i<lb;i++) a[i]=b[i]; for(int i=0;i<la;i++) b[i]=t[i]; int temp=la; la=lb; lb=temp; } if(la>lb) {//补零 int i,j=lb-1; for(i=la-1;i>=la-lb;i--) b[i]=b[j--]; for(;i>=0;i--) b[i]='0'; } int flag=0; for(int i=la;i>=1;i--){//相加 c[i]=(a[i-1]-'0'+b[i-1]-'0'+flag)%10+'0'; flag=(a[i-1]-'0'+b[i-1]-'0'+flag)/10; } if(flag){//是1补一输出,否则直接输出 c[0]='1'; for(int i=0;i<=la;i++) cout<<c[i]; cout<<endl; } else{ for(int i=1;i<=la;i++) cout<<c[i]; cout<<endl; } if(cot!=T) cout<<endl; cot++; } return 0; }