hdoj1002A + B Problem II(大数相加)

来源:互联网 发布:淘宝全套模板 编辑:程序博客网 时间:2024/05/17 06:13
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
 将大数用字符数组存起来然后将其存入数组中,对应相加,最后依次输出结果。代码如下:
#include<stdio.h>#include<string.h>#include<stdlib.h>int max(int x,int y){if(x<y)return y;else return x;}int main(){int t=0,n,numa[1010],numb[1010],i,j;char a[1010],b[1010];int lena,lenb;scanf("%d",&n);while(n--){memset(numa,0,sizeof(numa));memset(numb,0,sizeof(numb));scanf("%s%s",a,b);lena=strlen(a);lenb=strlen(b);for(i=0;i<lena;i++){numa[lena-1-i]=a[i]-'0';}for(i=0;i<lenb;i++){numb[lenb-1-i]=b[i]-'0';}int z=max(lena,lenb);for(i=0;i<z;i++){numa[i]=numa[i]+numb[i];if(numa[i]>9){numa[i]=numa[i]-10;numa[i+1]++;}}t++;printf("Case %d:\n",t);printf("%s + %s = ",a,b);if(numa[z]==0){for(i=z-1;i>=0;i--)printf("%d",numa[i]);printf("\n");}else{for(i=z;i>=0;i--)printf("%d",numa[i]);printf("\n");}if(n!=0)printf("\n");}}



0 0
原创粉丝点击