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
给这个坑题贵了。。。
输入有可能含前导0
比如001、000001之类
我是用c++写的,感觉理解起来方便些
我把输入的字符串反转,这样进位就好处理了
输出的时候逆序输出即可
代码如下:
#include <algorithm> #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <vector> #include <map> #define MAXN 100 #define INF 0x7FFFFFFF #define ll long long using namespace std; int main(void){ string str; string sum(150, '0'); while(cin>>str && str!="0"){ cin.ignore(); string chs(str.rbegin(), str.rend()); int ix = chs.size()-1; while(chs[ix] == '0') ix--; // cout << "chs = "; // for(int i=0; i<=ix; ++i) // cout << chs[i]; // cout << endl; for(int i=0; i<=ix; ++i){ sum[i] = (sum[i])+(chs[i]-'0'); for(int j=0; j<=i+1; ++j){//在这里处理进位,之前写 j<=i 就 WA 掉了 if(sum[j] > 57){ sum[j] -= 10; sum[j+1]++; } } } } string::iterator iter = sum.end()-1; while(*iter == '0') iter--; while(iter >= sum.begin()){ cout << *iter--; } cout << endl; return 0; }