报数
报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
1, 11, 21, 1211, 111221, ...
1
读作 "one 1"
-> 11
.
11
读作 "two 1s"
-> 21
.
21
读作 "one 2, then one 1"
-> 1211
.
给定一个整数 n
, 返回 第 n
个顺序。
注意事项
整数的顺序将表示为一个字符串。
样例
给定 n = 5
, 返回 "111221"
.
class Solution {
public:
/*
* @param n: the nth
* @return: the nth sequence
*/
string countAndSay(int n) {
// write your code here
string s="1";
if(n==1)
return s;
while(--n){
string tmp="";
int count=1;
for(int i=1;i<s.size();i++){
if(s[i]==s[i-1]){
count++;
}
else
{
tmp+=to_string(count)+s[i-1];// //to_string int转string;
//这里总是加上一个数,所以最后的一个数要额外补上 count=1; } } tmp+=to_string(count)+s.back();//最后的字符串加上,back()返回string的随后一个字符串 s=tmp; } return s; }};