ACM----HDU-1002 A + B Problem II

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
 
解题思路:根据题目要求,要实现两个非常大的整数相加,C++的数据类型已经无法满足题目要求。所以考虑按位对大数进行相加,而且特别需要注意进位问题。本位数字=(a+b+上一位的进位)%10,本位的进位=(a+b+上一位进位)/10。
注意:题目所要求的的输出格式及换行。
代码实现:
 1 #include<stdio.h>
 2 #include<string.h>
 3 
 4 int main(){
 5     int f;
 6     int i,an,bn,k,n,j;
 7     char a[1000],b[1000];
 8     scanf("%d",&n);
 9     getchar();
10     for(j=0;j<n;j++){
11         int af[1001]={0},bf[1001]={0},c[1001]={0};
12         scanf("%s%s",a,b);
13         an=strlen(a);bn=strlen(b);
14         k=an>bn?an:bn; 
15         for(i=0;i<an;i++)
16             af[i]=a[an-i-1]-'0';
17         for(i=0;i<bn;i++)
18             bf[i]=b[bn-i-1]-'0'; 
19         f=0;
20         for(i=0;i<k;i++){
21             c[i]=(af[i]+bf[i]+f)%10;
22             f=(af[i]+bf[i]+f)/10;
23         }   
24         printf("Case %d:\n",j+1);
25         printf("%s + %s = ",a,b);
26         if(f!=0)  printf("1");  
27         for(i=k-1;i>=0;i--) printf("%d",c[i]);
28         printf("\n");
29         if(j<n-1)printf("\n");        
30     }
31     
32 }

 

 

posted @ 2021-01-06 11:31  AA、  阅读(141)  评论(0编辑  收藏  举报