HDUacm 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
code:
1 #include <stdio.h>
2 #include <string.h>
3 main()
4 {
5 char a1[1001]={'\0'},b1[1001]={'\0'};
6 int a2[1001],b2[1001],sum[1001];
7 int n,i; //n 总次数,i 第i次
8 int la,lb,j,k,m,r;
9
10 scanf("%d",&n);
11 i=1;
12 while(i<=n)
13 {
14 for(j=0;j<1001;j++) //初始化
15 sum[j]=0;
16 for(j=0;j<1001;j++)
17 a2[j]=0;
18 for(j=0;j<1001;j++)
19 b2[j]=0;
20 scanf("%s",&a1);
21 scanf("%s",&b1);
22 la=strlen(a1);
23 lb=strlen(b1);
24 r=1;
25 for(j=la-1;j>=0;j--) //类型转换,将数字位置逆序
26 {
27 a2[r]=a1[j]-48;
28 r++;
29 }
30 r=1;
31 for(j=lb-1;j>=0;j--)
32 {
33 b2[r]=b1[j]-48;
34 r++;
35 }
36
37 if(la>lb) //以较大数的长度进行相加
38 k=la;
39 else
40 k=lb;
41 for(j=1;j<=k;j++)
42 {
43 sum[j]=sum[j]+a2[j]+b2[j];
44 if(sum[j]>=10) //进位
45 {
46 sum[j]=sum[j]-10;
47 m=j+1;
48 sum[m]++;
49 }
50 }
51
52 printf("case %d:\n",i); //输出结果,注意数字输出顺序
53 for(j=la;j>0;j--)
54 {
55 printf("%d",a2[j]);
56 }
57 printf(" + ");
58 for(j=lb;j>0;j--)
59 {
60 printf("%d",b2[j]);
61 }
62 printf(" = ");
63 if(sum[k+1])
64 k++;
65 for(j=k;j>0;j--)
66 {
67 printf("%d",sum[j]);
68 }
69 printf("\n");
70 if(i<n)
71 printf("\n");
72
73 i++;
74 }
75 }
tips:
1、本题为大整数相加类型,我先将大整数作为字符串读取,然后逐位转换为int型数,最后按位模拟求值;
2、多次读取字符时,务必注意对数组进行初始化操作(为此我牺牲了近半小时的时间debug);
3、注意可能存在的最高位的进位输出;
4、output a blank line between two test cases. --需要判断case数目;
5、you may assume the length of each integer will not exceed 1000. --将数组定义的大于题目范围,防止溢出;
6、字符串或char型数组的初始化可以使用‘\0’。
作者 任琦磊