A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 244704 Accepted Submission(s): 47183
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
解题
#include#include int main(){ int n,m,len1,len2,maxlen,minlen; char a[1010],b[1010],sum[1010]; char *max, *min; scanf("%d",&n); for(m=1;m<=n;m++) { int i,j,flag=0; memset(sum,0,sizeof(sum)); scanf("%s %s",a,b); len1=strlen(a); len2=strlen(b); if(len1>=len2)//判断字符串哪个长 { maxlen=len1; minlen=len2; max = a; min = b; } else { maxlen=len2; minlen=len1; max = b; min = a; } for(i=maxlen-1,j=minlen-1;i>=maxlen-minlen&&j>=0;i--,j--)//做循环把两字符串相加放到sum,用flag记录进位,大于9时候为1,并且sum-10, { //只加完到最短的(从后面开始加,方便输出从前面0下表开始输出) sum[i]+=max[i]+min[j]-'0'-'0'; if(i==0&&sum[0]>9) { flag=1; sum[0]-=10; } else if(sum[i]>9) { sum[i-1]+=1;//进位 sum[i]-=10;//减10 } } for(i=maxlen-minlen-1;i>=0;i--)//再加比最短的长出的部分的,从后面开始加。 { sum[i]+=max[i]-'0'; if(i==0&&sum[0]>9) { flag=1; sum[i]-=10; } else if(sum[i]>9) { sum[i-1]++;//进位 sum[i]-=10;//减10 } } // printf(" %d\n",flag); if(flag) //输出格式 { printf("Case %d:\n",m); printf("%s + %s = 1",a,b);}//a,b字符串不能修改,flag=1,sum[0]=0的时候的进位 else { printf("Case %d:\n",m); printf("%s + %s = ",a,b); } for(i=0;i