Sicily 1159. Sum
2015-12-30 14:17
435 查看
Time Limit: 1 secs, Memory Limit: 32 MB
Description
Given several positive integers, calculate the sum of them.
Input
There are several test cases, one line for each case. For each line, the first number, N (N<=100000), is the number of positive numbers and then N positive numbers followed. The sum will not exceed 10100.
Output
Output each sum in a single line without leading zeros.
Sample Input
3 1 2 3
1 123
2 1111111111111111111111111111111111 1111111111111111111111111111111111
Sample Output
6
123
2222222222222222222222222222222222
^_^ 不用多说,使用int,long long这些数据类型肯定是满足不了存储要求的,而使用string类型则方便对数对进行操作。get?
Description
Given several positive integers, calculate the sum of them.
Input
There are several test cases, one line for each case. For each line, the first number, N (N<=100000), is the number of positive numbers and then N positive numbers followed. The sum will not exceed 10100.
Output
Output each sum in a single line without leading zeros.
Sample Input
3 1 2 3
1 123
2 1111111111111111111111111111111111 1111111111111111111111111111111111
Sample Output
6
123
2222222222222222222222222222222222
^_^ 不用多说,使用int,long long这些数据类型肯定是满足不了存储要求的,而使用string类型则方便对数对进行操作。get?
#include <iostream> #include <string> #include <stack> using namespace std; string out_zero(string str1) // 去零 { string str; int j = 0; while (str1[j] == '0' && j < str1.size() - 1) j++; for (j; j < str1.size(); j++) str += str1[j]; return str; } string turn(string str1) // 翻转字符串 { string str; for (int i = str1.size() - 1; i >= 0; i--) str += str1[i]; return str; } string sum(string str1, string str2) { if (str2.size() > str1.size()) { string temp = str1; str1 = str2; str2 = temp; } str1 = turn(str1); str2 = turn(str2); int len1 = str1.size(); int len2 = str2.size(); str1 += '0'; //// for (int i = 0; i < len2; i++) { if ((str1[i] - 48) + (str2[i] - 48) <= 9) str1[i] = str1[i] + (str2[i] - 48); else { str1[i] = 48 + ((str1[i] - 48) + (str2[i] - 48) - 10); str1[i + 1] = str1[i + 1] + 1; } } for (int i = len2; i < len1; i++) { if (str1[i] >= 58) { str1[i] = 48 + ((str1[i] - 48) - 10); str1[i + 1] = str1[i + 1] + 1; } } return out_zero(turn(str1)); } int main() { int T; while (cin >> T && T > 0) { stack<string> pro; string str; for (int i = 0; i < T; i++) { cin >> str; pro.push(str); } while (pro.size() > 1) { string str1 = pro.top(); pro.pop(); string str2 = pro.top(); pro.pop(); pro.push(sum(str1, str2)); } cout << out_zero(pro.top()) << endl; } return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性