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

其它

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容