您的位置:首页 > 其它

HDU-1002 A + B Problem II

2012-02-17 21:09 323 查看
[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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
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

这个题 开个存数的数组 a[1001],然后把两串相加的结果存入a中 再对a中大于10的元素进行操作

#include<stdio.h>
#include<string.h>
int main()
{
char str1[1001],str2[1001],t[1001];
int n,f = 0,a[1001],i,j,flag,k1,k2,k,x,flag1;
scanf("%d", &n);
while(n--)
{
f++;//这个f是为了后面输出case 1。。。用的
memset(a,0,sizeof(a));//将a中全初始化为0
k = 0;//k是a的下标 最初为0
flag = 0;
flag1 = 0;
scanf("%s %s", str1,str2);
k1 = strlen(str1);
k2 = strlen(str2);
if(k1<k2)//让str1始终为大的
{
flag = 1;
strcpy(t,str1);
strcpy(str1,str2);
strcpy(str2,t);
x = k1;//把长度也交换下
k1 = k2;
k2 = x;
}
for(i = k1-1,j = k2-1 ; j>= 0 ;i--,j--)//开始从后往前加
{
a[k] = a[k]+str1[i]-'0'+str2[j]-'0';//因为是字符 -‘0’这里要注意是a[k]+因为a[k]有可能本来就有值
if(a[k]>=10)//把和存入k之后 判断一下k是否是大于10的
{
a[k+1] += a[k]/10;//把进上去的一位 存入a[k+1]中
a[k] = a[k]%10;//把各位留给a[k],这里两个语句不可相反
k++;
}
else
k++;
}
for(i = k1-k2-1 ; i >= 0 ; i--)//如果str1还没完的话 按照上面依次存入a中
{
a[k] = a[k]+str1[i]-'0';
if(a[k]>=10)
{
a[k+1] += a[k]/10;
a[k] = a[k]%10;
k++;
}
else
k++;
}
while(a[k] == 0)//把前面的0全筛掉
k--;
printf("Case %d:\n",f);
if(flag == 1)
printf("%s + %s = ",str2,str1);
else
printf("%s + %s = ",str1,str2);
for(i = k; i >= 0 ; i--)
{
printf("%d",a[i]);
flag1 = 1;//如果有输出 就标记下
}
if(flag1 == 0)//如果没输出 就说明全都是0 就是 0 0 相加了 直接输出 0
printf("0");
printf("\n");
if(n!=0)
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: