九度OJ 1119:Integer Inquiry(整数相加) (大数运算)
- 题目描述:
-
One of the first users of BIT's new supercomputer was Chip Diller.
He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
"This supercomputer is great,'' remarked Chip.
"I only wish Timothy were here to see these results.''
(Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.)
- 输入:
-
The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no VeryLongInteger will be negative).
The final input line will contain a single zero on a line by itself.
- 输出:
-
Your program should output the sum of the VeryLongIntegers given in the input.
- 样例输入:
-
123456789012345678901234567890 123456789012345678901234567890 123456789012345678901234567890 0
- 样例输出:
-
370370367037037036703703703670
- 提示:
-
注意输入数据中,VeryLongInteger 可能有前导0
思路:
大数运算类题目,用字符串或数组来做。
代码:
#include <stdio.h> #include <string.h> #define M 105 void print(int *a) { int i, j; for (i=0; i<M; i++) { if (a[i] != 0) break; } if (i == M) printf("0\n"); else { for (j=i; j<M; j++) printf("%d", a[j]); printf("\n"); } } int main(void) { int n, i, j; int a[M], b[M]; char s[M]; memset(a, 0, M*sizeof(int)); while (scanf("%s", s) != EOF) { if (strcmp(s, "0") == 0) break; memset(b, 0, M*sizeof(int)); n = strlen(s); j = M-n; for (i=0; i<n; i++) b[j++] = s[i]-'0'; for (i=M-1; i>0; i--) { a[i] += b[i]; if (a[i] >= 10) { a[i-1] ++; a[i] -= 10; } } } print(a); return 0; } /************************************************************** Problem: 1119 User: liangrx06 Language: C Result: Accepted Time:0 ms Memory:912 kb ****************************************************************/