A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 340103 Accepted Submission(s): 65964
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
1 #include <stdio.h> 2 #include <string.h> 3 #define MAXSIZE 1005 4 5 int main() 6 { 7 char temp1[MAXSIZE],temp2[MAXSIZE]; 8 int cases; 9 scanf("%d",&cases); 10 int fuck=cases; 11 while(cases--){ 12 int i,j; 13 scanf("%s",temp1); 14 scanf("%s",temp2); 15 int len1=strlen(temp1),len2=strlen(temp2); 16 17 /*将两个数反转*/ 18 char val1[MAXSIZE],val2[MAXSIZE]; 19 for(i=len1-1,j=0;i>=0;--i) 20 val1[j++]=temp1[i]; 21 val1[j]='\0'; 22 for(i=len2-1,j=0;i>=0;--i) 23 val2[j++]=temp2[i]; 24 val2[j]='\0'; 25 26 /*将长度小的数的高位用0补齐*/ 27 int max_len=(len1>len2)?len1:len2; 28 if(len1!=len2){ 29 30 if(len1<len2){ 31 for(i=len1;i<len2;++i) 32 val1[i]='0'; 33 val1[len2]='\0'; 34 } 35 else{ 36 for(i=len2;i<len1;++i) 37 val2[i]='0'; 38 val2[len1]='\0'; 39 } 40 } 41 42 /*每个位做加法(进位)*/ 43 int flag=0,over=0; 44 char res[MAXSIZE]; 45 for(i=0;i<max_len;i++){ 46 int sum=val1[i]+val2[i]-2*'0'+flag; 47 if(sum>9){ 48 if(i==(max_len-1)) 49 over=1; 50 flag=1; 51 res[i]=sum-10+'0'; 52 } 53 else{ 54 flag=0; 55 res[i]=sum+'0'; 56 } 57 } 58 59 /*注意考虑第一位进位导致res长度大于max_len的情况*/ 60 if(over) 61 res[max_len++]=flag+'0'; 62 res[max_len]='\0'; 63 64 /*逐个打印*/ 65 printf("Case %d:\n",fuck-cases); 66 printf("%s + %s = ",temp1,temp2); 67 for(i=max_len-1;i>=0;--i) 68 putchar(res[i]); 69 if(cases!=0) 70 printf("\n\n"); 71 else 72 putchar('\n'); 73 } 74 return 0; 75 }