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
 
这个题 开个存数的数组 a[1001],然后把两串相加的结果存入a中 再对a中大于10的元素进行操作
 1 #include<stdio.h>
2 #include<string.h>
3 int main()
4 {
5 char str1[1001],str2[1001],t[1001];
6 int n,f = 0,a[1001],i,j,flag,k1,k2,k,x,flag1;
7 scanf("%d", &n);
8 while(n--)
9 {
10 f++;//这个f是为了后面输出case 1。。。用的
11 memset(a,0,sizeof(a));//将a中全初始化为0
12 k = 0;//k是a的下标 最初为0
13 flag = 0;
14 flag1 = 0;
15 scanf("%s %s", str1,str2);
16 k1 = strlen(str1);
17 k2 = strlen(str2);
18 if(k1<k2)//让str1始终为大的
19 {
20 flag = 1;
21 strcpy(t,str1);
22 strcpy(str1,str2);
23 strcpy(str2,t);
24 x = k1;//把长度也交换下
25 k1 = k2;
26 k2 = x;
27 }
28 for(i = k1-1,j = k2-1 ; j>= 0 ;i--,j--)//开始从后往前加
29 {
30 a[k] = a[k]+str1[i]-'0'+str2[j]-'0';//因为是字符 -‘0’这里要注意是a[k]+因为a[k]有可能本来就有值
31 if(a[k]>=10)//把和存入k之后 判断一下k是否是大于10的
32 {
33 a[k+1] += a[k]/10;//把进上去的一位 存入a[k+1]中
34 a[k] = a[k]%10;//把各位留给a[k],这里两个语句不可相反
35 k++;
36 }
37 else
38 k++;
39 }
40 for(i = k1-k2-1 ; i >= 0 ; i--)//如果str1还没完的话 按照上面依次存入a中
41 {
42 a[k] = a[k]+str1[i]-'0';
43 if(a[k]>=10)
44 {
45 a[k+1] += a[k]/10;
46 a[k] = a[k]%10;
47 k++;
48 }
49 else
50 k++;
51 }
52 while(a[k] == 0)//把前面的0全筛掉
53 k--;
54 printf("Case %d:\n",f);
55 if(flag == 1)
56 printf("%s + %s = ",str2,str1);
57 else
58 printf("%s + %s = ",str1,str2);
59 for(i = k; i >= 0 ; i--)
60 {
61 printf("%d",a[i]);
62 flag1 = 1;//如果有输出 就标记下
63 }
64 if(flag1 == 0)//如果没输出 就说明全都是0 就是 0 0 相加了 直接输出 0
65 printf("0");
66 printf("\n");
67 if(n!=0)
68 printf("\n");
69 }
70 return 0;
71 }

你可能感兴趣的:(HDU)