A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 208611 Accepted Submission(s): 40103
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
2 1 2 112233445566778899 998877665544332211
Sample Output
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
大数相加
分别用字符串a,和字符串b,来存储两个不同的数,用字符串c进行保存
将字符串的每位通过 -'0'来得到相应的整数
从后往前,逐一对每位进行相加,如果结果>=10,则下一位的字符串+1,当前结果 -10,并保存
接下来对于剩下的位进行考虑,如果k>0则表明还有剩下,则把剩下的位,对c进行赋值
#include <stdio.h>
#include <string.h>
const int N = 1000;
int main() {
int n,p;//辅助变量
char a[N],b[N],c[N]={0},d[N]={0};//c用于倒叙输出
int len1,len2;
int sum;
scanf("%d",&n);
for(int i=0;i<n;i++) {
printf("Case %d:\n",i+1);
scanf("%s%s",a,b);
len1 = strlen(a);
len2 = strlen(b);
len1--;
len2--;
printf("%s + %s = ",a,b);
p=0;
while(len1 >=0 && len2>=0) {
sum = c[p] + (a[len1]-'0')+(b[len2]-'0');
if( sum >= 10) {
c[p]=sum-10+'0';
c[p+1]++;
}
else {
c[p]=sum+'0';
}
p++;
len1--;
len2--;
}
//将剩下的位数补给c
if(len1 >= 0) {
while(len1 >=0 ) {
sum = c[p]+a[len1]-'0';
if( sum >= 10) {
c[p]=sum-10+'0';
c[p+1]++;
}
else
c[p]=sum+'0';
p++;
len1--;
}
}
else if(len2 >= 0) {
while(len2 >= 0) {
sum = c[p]+b[len2]-'0';
if( sum >= 10) {
c[p]=sum-10+'0';
c[p+1]=1;
}
else
c[p]=sum+'0';
p++;
len2--;
}
}
for(int j=p-1,k=0;j>=0;j--,k++) {
d[j]=c[k];
}
d[p]='\0';
printf("%s\n",d);
if( i+1 != n)//对于2组之间加空行
printf("\n");
memset(c,0,sizeof(c));//将数组c清零
}
return 0;
}