Integer Inquiry
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.)
Input
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.
Output
Your program should output the sum of the VeryLongIntegers given in the input.
Sample Input
123456789012345678901234567890 123456789012345678901234567890 123456789012345678901234567890 0
Sample Output
370370367037037036703703703670
这题也就是高精度加法,以字符串读入各行数字,然后以逆序存入整形数组中,通过数组进行运算,大于9就进位,同时取余。
#include <iostream>
#include <cstring>
using namespace std;
const int N = 150;
int main() {
char temporary[N];
int interger[N];
int sum[N];
memset(temporary,0,sizeof(temporary));
memset(sum,0,sizeof(sum));
while (cin >> temporary) {
if (!strcmp(temporary,"0"))
break;
int lengthOftemporary = strlen(temporary);
for (int i = 0,j = lengthOftemporary-1; j >= 0; i++,j--)
interger[i] = temporary[j] - '0';
for (int i = 0; i < lengthOftemporary; i++) {
sum[i] += interger[i];
if (sum[i] > 9) {
sum[i+1] += sum[i] / 10;
sum[i] %= 10;
}
}
memset(temporary,0,sizeof(temporary));
memset(interger,0,sizeof(interger));
}
int lengthOfSum = N;
for (int i = N-1; i >= 0 && !sum[i]; i--)
lengthOfSum = i;
for (int i = lengthOfSum-1; i >= 0; i--)
cout << sum[i];
if (lengthOfSum == 0)
cout << '0';
cout << endl;
return 0;
}