您的位置:首页 > 其它

HDOJ 1002 A + B Problem II

2012-02-23 03:20 316 查看
[align=left]Problem Description[/align]
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.
[align=left]Sample Input[/align]

2
  1 2
112233445566778899 998877665544332211

[align=left]Sample Output[/align]

Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

Code:

#include <stdio.h>
#include <string.h>
main()
{
char a1[1001]={'\0'},b1[1001]={'\0'};
int a2[1001],b2[1001],sum[1001];
int n,i;        //n 总次数,i 第i次
int la,lb,j,k,m,r;

scanf("%d",&n);
i=1;
while(i<=n)
{
for(j=0;j<1001;j++) //初始化
sum[j]=0;
for(j=0;j<1001;j++)
a2[j]=0;
for(j=0;j<1001;j++)
b2[j]=0;
scanf("%s",&a1);
scanf("%s",&b1);
la=strlen(a1);
lb=strlen(b1);
r=1;
for(j=la-1;j>=0;j--) //类型转换,将数字位置逆序
{
a2[r]=a1[j]-48;
r++;
}
r=1;
for(j=lb-1;j>=0;j--)
{
b2[r]=b1[j]-48;
r++;
}

if(la>lb)  //以较大数的长度进行相加
k=la;
else
k=lb;
for(j=1;j<=k;j++)
{
sum[j]=sum[j]+a2[j]+b2[j];
if(sum[j]>=10)  //进位
{
sum[j]=sum[j]-10;
m=j+1;
sum[m]++;
}
}

printf("Case %d:\n",i);  //输出结果,注意数字输出顺序
for(j=la;j>0;j--)
{
printf("%d",a2[j]);
}
printf(" + ");
for(j=lb;j>0;j--)
{
printf("%d",b2[j]);
}
printf(" = ");
if(sum[k+1])
k++;
for(j=k;j>0;j--)
{
printf("%d",sum[j]);
}
printf("\n");
if(i<n)
printf("\n");

i++;
}
}


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’。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: