A + B Problem(大数相加)
输入
输入的第一行包含一个整数 T(1<=T<=20),表示测试用例的数量。然后是 T 行,每行由两个正整数 A 和 B 组成。注意整数非常大,这意味着您不应该使用 32 位整数来处理它们。您可以假设每个整数的长度不会超过 1000。
输出
对于每个测试用例,您应该输出两行。第一行是“Case #:”,#表示测试用例的编号。第二行是等式“A + B = Sum”,Sum 表示 A + B 的结果。注意等式中有一些空格。在两个测试用例之间输出一个空行。
Sample Input
2
1 2
112233445566778899 998877665544332211
Sample Output
Case 1:
1 + 2 = 3
Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110
#include<stdio.h>
#include<string.h>
int max(int a,int b){
if(a>=b)
return a;
if(a<b)
return b;
}
int min(int a,int b){
if(a>=b)
return b;
if(a<b)
return a;
}
void Reverse(char *a){
char* start = a, *end = a+strlen(a)-1;
char temp;
while (start <end){
temp =*start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main(){
int n,len1,len2,k=0,i,t,l=1,m=0;
char a[1005],b[1005],sum[1005]={0};
scanf("%d",&n);
while(n--){
scanf("%s %s",&a,&b);
len1=strlen(a);
len2=strlen(b);
printf("Case %d:\n",l);
l++;
printf("%s + %s = ",a,b);
Reverse(a);
Reverse(b);
for(i=0;i<=min(len1,len2)-1;i++){
t=a[i]-'0'+b[i]-'0'+m;
sum[k++]+=t%10;
m=t/10;
}
if(len1!=len2){
for(i=min(len1,len2);i<=max(len1,len2)-1;i++){
if(len1>len2)
t=a[i]-'0'+m;
else
t=b[i]-'0'+m;
sum[k++]+=t%10;
m=t/10;
}
}
if((i==min(len1,len2)||i==max(len1,len2))&&m!=0)
sum[k++]+=m;
for(i=k-1;i>=0;i--)
printf("%d",sum[i]);
printf("\n");
if(n!=0)
printf("\n");
k=0;
memset(sum,0,sizeof(sum));
}
return 0;
}