Sum of numbers from 0 to N -- 7 Kyu

原题

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

分析

本题包含两部分处理:

  1. 字符串连接
  2. 数字求和

参考答案

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

其它

你可能感兴趣的:(Sum of numbers from 0 to N -- 7 Kyu)