報數序列是指一個整數序列,按照其中的整數的順序進行報數,得到下一個數。其前五項如下:
1. 1 2. 11 3. 21 4. 1211 5. 111221
1
被讀作 "one 1"
("一個一"
) , 即 11
。11
被讀作 "two 1s"
("兩個一"
), 即 21
。21
被讀作 "one 2"
, "one 1"
("一個二"
, "一個一"
) , 即 1211
。
給定一個正整數 n ,輸出報數序列的第 n 項。
注意:整數順序將表示爲一個字符串。
示例 1:
輸入: 1 輸出: "1"
示例 2:
輸入: 4 輸出: "1211"
//報數;
#include<iostream>
#include<string>
using namespace std;
class Solution {
public:
string countAndSay(int n) {
if (n == 1)
return "1";
else {
string output = countAndSay(n - 1);
string result;
int index = 0;
int cur_step = index;
while (index <output.size())
{
char curr_ch = output[index];
int count = 0;
while (output[cur_step] == curr_ch &&cur_step<=output.size())
{
cur_step++;
count++;
}
char number = count + '0'; //!!!!將int型轉變爲char型;數字2的char型是50,所以加‘0’;
result += number;
result += curr_ch;
index = cur_step;
}
return result;
}
}
};
int main()
{
Solution item;
cout << item.countAndSay(6) << endl;
system("pause");
return 0;
}