问题描述
在C/C++语言中,整型所能表示的范围一般为-231到231(大约21亿),即使long long型,一般也只能表示到-263到263。要想计算更加规模的数,就要用软件来扩展了,比如用数组或字符串来模拟更多规模的数及共运算。
现在输入两个整数,请输出它们的和。
输入格式
两行,每行一个整数,每个整数不超过1000位
输出格式
一行,两个整数的和。
样例输入
15464315464465465
482321654151
样例输出
15464797786119616
数据规模和约定
每个整数不超过1000位
#include <stdio.h>
#include <string.h>
#define BASE 10
#define N 2000
char a[N+1], b[N+1];
char ans[N+1];
int main(void)
{
int anslen, carry, len, i, j;
scanf("%s", a);
scanf("%s", b);
memset(ans, 0, sizeof(ans));
anslen = len = strlen(a);
for(i=len-1, j=0; i>=0; i--)
ans[j++] = a[i] - '0';
len = strlen(b);
if(len > anslen)
anslen = len;
carry = 0;
for(i=len-1, j=0; i>=0; i--,j++) {
ans[j] += b[i] - '0' + carry;
carry = ans[j] / BASE;
ans[j] %= BASE;
}
while(carry > 0) {
ans[j] += carry;
carry = ans[j] / BASE;
ans[j++] %= BASE;
}
if(j > anslen)
anslen = j;
/* 去除前导的多个0 */
for(i=anslen-1; i>=0; i--)
if(ans[i])
break;
if(i < 0)
i = 0;
/* 输出结果 */
for(; i>=0; i--)
printf("%d", ans[i]);
printf("\n");
return 0;
}