1001 Sum Problem

1001 Sum Problem,第1张

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

#include

#include

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;

}

尽管上述解答1Accepted,但我认为有点不合题意。


因为输入要求是多行一次性输入,然后再输出。


而解答1在键盘输入只能是输入一行立即输出结果。


为什么能Accepted呢,个人猜测是OJ的测试用例是以文件方式一次性读入的。


那如何通过键盘多行输入后再输出呢?解答2用getline()函数来接收键盘输入并忽略回车键,通过vector来存储输入。


解答2:

#include

#include

#include

#include

#include

using namespace std;

int main()

{

    string n;

    int sum;

    vector 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;

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/584967.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-12
下一篇 2022-04-12

发表评论

登录后才能评论

评论列表(0条)

保存