描述
The count-and-say sequence is the sequence of integers beginning as follows:
1
, 11
, 21
, 1211
, 111221
, …
1
is read off as "one 1"
or 11
.
11
is read off as "two 1s"
or 21
.
21
is read off as "one 2
, then one 1"
or 1211
.
Given an integer n, generate the nth sequence.
分析
要获得这一序列的第n个数,直接按照题目的要求进行模拟,输出即可。
解决方案1(C++)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public: string countAndSay(int n) { string res = "1"; for(int i = 2; i <= n; i++) { int j = 0; string nowstring; while(j < res.size()) { int numberof_j = 0; for(numberof_j = j+1; numberof_j < res.size(); numberof_j++) { if(res[numberof_j] != res[j]) break; } nowstring.push_back(numberof_j-j+'0'); nowstring.push_back(res[j]); j = numberof_j; } res = nowstring; } return res; } };
|
相关问题
(M) Encode and Decode Strings