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. 數(shù)字求和

參考答案

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

說明

  • 單獨數(shù)字轉(zhuǎn)字符串可使用to_string() (C++11)
  • 多個數(shù)字轉(zhuǎn)字符串可使用ostringstream
  • 多個數(shù)字有序數(shù)列求和,可用高斯求和公式n*(n+1)/2

其它

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容