这题要用高精度加法来做
参考:http://www.oschina.net/code/snippet_564999_11104
随手写了一下,没有测试大量数据,不保证完全正确
#include
#include
#define MAXSIZE 100
void add(char *num1, char *num2, char*ans)
{
int i, j;
// 逆向赋值
// 例如num1 = "123456"
// 则a = "654321000000...0"(后面用0填充)
// b同理
char a[MAXSIZE + 2], b[MAXSIZE + 2], c[MAXSIZE + 2];
for(i=0; i < MAXSIZE + 1; i++)
{
a[i] = b[i] = c[i] = '0';
}
a[MAXSIZE + 1] = b[MAXSIZE + 1] = c[MAXSIZE + 1] = '\0';
for(i=0; i < strlen(num1); i++)
{
a[i] = num1[strlen(num1) - 1 - i];
}
for(i=0; i < strlen(num2); i++)
{
b[i] = num2[strlen(num2) - 1 - i];
}
for(i=0; i < MAXSIZE + 1; i++)
{
char iAns = c[i] - '0'; //ascii转为数字
char iA = a[i] - '0';
char iB = b[i] - '0';
iAns += iA + iB;
char iJW = iAns / 10; //处理进位
iAns %= 10;
c[i] = iAns + '0';
c[i + 1] = iJW + '0';
}
//除去前端的0
//将结果逆向赋值给ans
//返回ans
for(i=MAXSIZE; (i>=0) && (c[i]=='0'); i--);
if(i == -1) strcpy(ans, "0");
else
{
for(j = 0; j <= i; j++)
{
ans[j] = c[i - j];
}
ans[j] = '\0';
}
}
int main(int argc, char* argv[])
{
char a[MAXSIZE + 2], b[MAXSIZE + 2], ans[MAXSIZE + 2];
while(1)
{
scanf("%s %s", a, b);
if((strcmp(a, "0")==0) && (strcmp(b, "0")==0)) break;
add(a, b, ans);
printf("%s\n", ans);
}
return 0;
}