In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
Input
The input will consist of a series of integers n, one integer per line.
Output
For each case, output SUM(n) in one line, followed by a blank line.You may assume the result will be in the range of 32-bit signed integer.
Sample Input
1
100
Sample Output
1
5050
解答1:
#include <iostream>
using namespace std;
int main()
{
int n, sum;
while (cin >> n)
{
//"You may assume the result will be in the range of 32-bit signed integer."
//注意到上面的提示,为了防止n*(n+1)溢出,利用n的奇偶性,先行除以2。
if (n % 2 == 0)
sum = n / 2 * (n + 1);
else
sum = (n + 1) / 2 * n;
cout << sum << endl << endl;
}
return 0;
}
尽管上述解答1 Accepted,但我认为有点不合题意。因为输入要求是多行一次性输入,然后再输出。而解答1在键盘输入只能是输入一行立即输出结果。为什么能Accepted呢,个人猜测是OJ的测试用例是以文件方式一次性读入的。那如何通过键盘多行输入后再输出呢?解答2用getline()函数来接收键盘输入并忽略回车键,通过vector来存储输入。
解答2:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string n;
int sum;
vector<string> vecStr;
while (getline(cin, n))
{
if (n.size() == 0) break; //结束循环输入
vecStr.push_back(n);
}
for (auto j : vecStr)
{
int i = atoi(j.c_str());
if (i % 2 == 0)
sum = i / 2 * (i + 1);
else
sum = (i + 1) / 2 * i;
cout << sum << endl << endl;
}
return 0;
}