您的位置:首页 > 编程语言 > C语言/C++

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?

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sicily C++