题目:http://acm.gdufe.edu.cn/Problem/read/id/1002
A+B(Big Number Version)
Time Limit: 2000/1000ms (Java/Others)
Problem Description:
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 400.
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:
3 1 2 112233445566778899 998877665544332211 33333333333333333333333333 100000000000000000000
Sample Output:
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110 Case 3: 33333333333333333333333333 + 100000000000000000000 = 33333433333333333333333333
思路:400位数啊,明显是unusigned long long int是不够大的,所以就要自己写一个。所以我就想,把最后一位数相加,然后把十位数加到前一位数上(如果没有十位数,那就是0),最后把整个数输出来,因为不知道具体有多少位数,所以两个数的和我是倒着储存的(能看懂我的意思吗==)
难度:感觉有一定的难度,想了很长时间,主要是写的时候觉得有难度,想出来不算很难吧。要把字符串转变成整数数组。
代码:
1 #include<stdio.h> 2 #include<string.h> 3 int main() 4 { 5 int n; 6 while(scanf("%d",&n)!=EOF) 7 { 8 char ai[400],bi[400]; 9 int i,j,d,e,k,q=0,a[400],b[400],c[400]; 10 while(n--) 11 { 12 q++; 13 getchar(); 14 scanf("%s",ai); 15 scanf("%s",bi); 16 d=strlen(ai); 17 e=strlen(bi); 18 for(i=0;i<d;i++) 19 a[i]=ai[i]-'0'; 20 for(j=0;j<e;j++) 21 b[j]=bi[j]-'0'; 22 k=0; 23 c[0]=a[d-1]+b[e-1]; 24 if(d>1||e>1) 25 for(k=1,i=d-2,j=e-2;;i--,j--,k++) 26 { 27 if(i>=0&&j>=0) 28 c[k]=c[k-1]/10+a[i]+b[j]; 29 else if(i>=0&&j<0) 30 c[k]=c[k-1]/10+a[i]; 31 else if(i<0&&j>=0) 32 c[k]=c[k-1]/10+b[j]; 33 else if(i<0&&j<0) 34 {if(c[k-1]>=10) 35 c[k]=1; 36 else k--;break;} 37 } 38 printf("Case %d: ",q); 39 printf("%s + %s = ",ai,bi); 40 for(;k>=0;k--) 41 {c[k]=c[k]%10; 42 printf("%d",c[k]); 43 } 44 printf(" "); 45 if(n>0) 46 printf(" "); 47 } 48 } 49 return 0; 50 }