HDOJ-1002
Problem DescriptionI have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
InputThe 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.
OutputFor 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 Input2 1 2 112233445566778899 998877665544332211
Sample OutputCase 1: 1 + 2 = 3Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
大数相加的问题,开两个数组分别储存a、b,再开一个数组sum用来储存最终的和值。
这题要注意相加时储存的顺序和最后输出时的顺序不要搞错。
当然,这里特别强调一下最后的输出格式,最后一组数据只要换一行!一行!行!原谅愚蠢如我在这个点被坑了5次!!还是刷题太少。。
附AC代码
1 #include<cstdio> 2 #include<cstring> 3 const int MAX=1050; 4 int main() 5 { 6 int n,m,len1,len2,maxlen,minlen; 7 char a[MAX],b[MAX],sum[MAX];//三个主要数组 8 char *max, *min; 9 scanf("%d",&n); 10 for(m=1;m<=n;m++) 11 { 12 int i,j,flag=0; 13 memset(sum,0,sizeof(sum)); 14 scanf("%s %s",&a,&b); 15 len1=strlen(a); 16 len2=strlen(b); 17 if(len1>=len2)//判断长度,长的为max 18 { 19 maxlen=len1; 20 minlen=len2; 21 max = a; 22 min = b; 23 } 24 else 25 { 26 maxlen=len2; 27 minlen=len1; 28 max = b; 29 min = a; 30 } 31 for(i=maxlen-1,j=minlen-1;i>=maxlen-minlen&&j>=0;i--,j--)//长度重叠部分相加 32 { 33 sum[i]+=max[i]+min[j]-'0'-'0';//转换为十进制整数,下面的同理 34 if(i==0&&sum[0]>9)//如果两数组长度相等 35 { 36 flag=1;//加在sum前表示进的1 37 sum[i]-=10;//本大于9,进1故减10 38 } 39 else if(sum[i]>9) 40 { 41 sum[i-1]++;//进1 42 sum[i]-=10; 43 } 44 } 45 for(i=maxlen-minlen-1;i>=0;i--)//剩下的max加到sum里 46 { 47 sum[i]+=max[i]-'0'; 48 if(i==0&&sum[0]>9) 49 { 50 flag=1; 51 sum[i]-=10; 52 } 53 else if(sum[i]>9) 54 { 55 sum[i-1]++; 56 sum[i]-=10; 57 } 58 }printf("Case %d:\n",m); 59 60 if(flag) 61 { 62 63 printf("%s + %s = 1",a,b);} 64 else 65 { 66 67 printf("%s + %s = ",a,b); 68 } 69 for(i=0;i<maxlen;i++) 70 printf("%d",sum[i]); 71 if(m!=n){ //注意这里最后一组的输出 72 printf("\n\n"); 73 } 74 else{ 75 {printf("\n");} 76 } 77 } 78 return 0; 79 }