HDU 1002 A + B Problem II

来源:互联网 发布:萤石云ddns设备域名 编辑:程序博客网 时间:2024/06/02 00:47
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
21 2112233445566778899 998877665544332211
 

Sample Output
Case 1:1 + 2 = 3Case 2:112233445566778899 + 998877665544332211 = 1111111111111111110
 

Author

Ignatius.L



题目大意:

两个整数A和B的相加工作,输入一个整数T(1 <= T <= 20)输入的整数是非常大的,这意味着不应该使用32位整数处他们,这就是一个大数相加的题目

解题思路:

既然传统的相加方法已经满足不了我们的需求,再这样的条件下我们利用数组的形式对每一位进行操作,在数组中按照顺序将大数的每一位放入数组中,在通过数组运算得到最终结果。步骤大致是在输入大数的时候就直接将其输入到对应的数组位置当中,并通过分析每个大数的长度来完成相加进位等操作。然后再利用数组将结果输出。主要还是考察了对数组的运用。数组拥有广的应用领域。非常值得学习,掌握其灵活的用法

#include<stdio.h>#include<string.h>int shu(char a){return (a-'0');}int main(){char a[1000];char b[1000];int num[1000];int n,j=1,al,bl,k,t;scanf("%d",&n);//输入 while(n--)//循环 {if(j!=1)//如果j不等于1 {printf("\n");//换行 }scanf("%s",a);//输入a al=strlen(a);//计算长度 scanf("%s",b);//输入b bl=strlen(b);//计算长度        k=(al>bl)?al:bl;//选择最大长度,并将最大长度给K for(int i=0;i<=k;i++)//对数组num进行长度为K的初始化 {num[i]=0;} t=k;//将最大值付给T for(k;al>0&&bl>0;k--)//a的长度大于零b的长度大于零,数组一位一位比较        {           num[k]+=shu(a[--al])+shu(b[--bl]);//           if(num[k]/10)           {               num[k-1]++;//进位                num[k]%=10;//余数留在本位            }       }       while(al>0)//a比b多出来的部分        {    num[k--]+=shu(a[--al]);if(num[k+1]/10)            {        num[k]++;                num[k+1]%=10;           }       }       while(bl>0)//b比a多出来的部分        {        num[k--]+=shu(b[--bl]);if(num[k+1]/10)           {               num[k]++;               num[k+1]%=10;           }       }       printf("Case %d:\n",j++);//输出Case        printf("%s + %s = ",a,b);        for(int i=0;i<=t;i++)       {           if(i==0&&num[i]==0)           i++;           printf("%d",num[i]);       }       printf("\n");   }   return 0;}


0 0
原创粉丝点击