Description
A and B are both integers, which have at most 300 decimal digits. Please calculate their sum.
Input
Each line of the input contains two decimal integers A and B separated with a space character. (0<=A,B<10^300)
Output
For each line of input, print the value of A+B in decimal form on a line by itself.
Sample Input
1 1
1234567890 10000000010
Sample Output
2
11234567900
分析
两个大整数相加,最多300位,先按字符串读入,之后挨个字符转化为数字相加,并进位。最后如果哪个数有多余的数,再加在一块。
#include"stdio.h"
int main()
{
char a[301],b[301];
while(scanf("%s %s",a,b)!=EOF)
{
//printf("%s %s\n",a,b);
int alength=0,blength=0;
while(a[alength]!='\0')alength++;
while(b[blength]!='\0')blength++;
//printf("%d %d\n",alength,blength);
int c[302];
for(int i=0;i<302;i++)
c[i]=0;
int i=alength-1,j=blength-1,clength=0;
while(i>=0&&j>=0)
{
int temp=a[i]-'0'+b[j]-'0'+c[clength];
if(temp>=10) {c[clength]=temp%10;c[clength+1]=temp/10;}
else c[clength]=temp;
i--;
j--;
clength++;
}
while(i>=0)
{
int temp=a[i]-'0'+c[clength];
if(temp>=10) {c[clength]=temp%10;c[clength+1]=temp/10;}
else c[clength]=temp;
i--;
clength++;
}
while(j>=0)
{
int temp=b[j]-'0'+c[clength];
if(temp>=10) {c[clength]=temp%10;c[clength+1]=temp/10;}
else c[clength]=temp;
j--;
clength++;
}
if(c[clength]!=0)clength++;
for(int k=clength-1;k>=0;k--)
printf("%d",c[k]);
printf("\n");
}
}