COJ - 1049 - Sum 题解

来源:互联网 发布:在线视频网站cms 编辑:程序博客网 时间:2024/05/16 14:36

1049 - Sum

Description

Your task is to find the sum of all integer numbers lying between 1 and N inclusive.

Input specification

The input consists of a single integer N that is not greater than 10^4 by it's absolute value.

Output specification

Write to the output a single integer number that is the sum of all integer numbers lying between 1 and N inclusive.

Sample input

3

Sample output

6


这里有个小陷阱,需要处理负数的问题:

void sumMinusAndPositives(){int n = 0;cin>>n;int t = n < 0? -n : n;int ans = (n < 0) ? (1 - ((1+t)*t) / 2) : (((1+t)*t) / 2);if (0 == n) ans = 1;cout<<ans<<endl;}





0 0