北大ACM1503——Integer Inquiry

来源:互联网 发布:网络成瘾综合症 编辑:程序博客网 时间:2024/06/11 02:05

这题,很简单,高精度加法。

写的比较冗长。还可以缩短代码。输入的时候,直接加起来,最后取余输出。

下面的是AC的代码:

#include <iostream>#include <cstdio>#include <cstring>using namespace std;char ans[200];char temp[150];void add(){int length1 = strlen(ans);int length2 = strlen(temp);int i, j, k, num[150];k = 0;for(i = length1 - 1, j = length2 - 1; i >= 0 && j >= 0; i--, j--){num[k++] = ans[i] + temp[j] - 2 * '0';}while(i >= 0)num[k++] = ans[i--] - '0';while(j >= 0)num[k++] = temp[j--] - '0';for(i = 0; i < k - 1; i++){if(num[i] >= 10){num[i + 1] += num[i] / 10;num[i] %= 10;}}if(num[k - 1] >= 10){num[k] = num[k - 1] / 10;num[k - 1] %= 10;k++;}j = 0;for(i = k - 1; i >= 0; i--){ans[j++] = num[i] + '0';}ans[j] = '\0';}int main(){memset(ans, '\0', sizeof(ans));memset(temp, '\0', sizeof(temp));while(scanf("%s", temp) != EOF){getchar();if(!strcmp(temp, "0"))break;if(strlen(ans) == 0)strcpy(ans, temp);else{add();}}printf("%s\n", ans);return 0;}


1 0