原题
https://www.codewars.com/kata/56e9e4f516bcaa8d4f001763/train/cpp
题目
- Description:
We want to generate a function that computes the series starting from 0 and ending until the given number following the sequence:
0 1 3 6 10 15 21 28 36 45 55 ....
which is created by
0, 0+1, 0+1+2, 0+1+2+3, 0+1+2+3+4, 0+1+2+3+4+5, 0+1+2+3+4+5+6, 0+1+2+3+4+5+6+7 etc..
Input:LastNumber
Output:series and result
- Example:
Input:
> 6
Output:
0+1+2+3+4+5+6 = 21
Input:
> -15
Output:
-15<0
Input:
> 0
Output:
0=0
分析
本题包含两部分处理:
- 字符串连接
- 数字求和
参考答案
using namespace std;
class SequenceSum{
int count;
public:
SequenceSum (int);
string showSequence();
};
string SequenceSum::showSequence(){
if(0 == count) return "0=0";
if(0 > count) return to_string(count) + "<0";
ostringstream oss;
for(size_t i=0;i<=count;i++){
oss << i;
if(i!=count)
oss <<"+";
else
oss << " = " << (count*(count+1)>>1);
}
return oss.str();
}
SequenceSum::SequenceSum (int c) {
count = c;
}
说明
- 单独数字转字符串可使用
to_string()
(C++11) - 多个数字转字符串可使用
ostringstream
- 多个数字有序数列求和,可用高斯求和公式
n*(n+1)/2