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.
Note: The sequence of integers will be represented as a string.
第一次出现的是1,第二次出现的是11,第三次出现的是21,第四次出现的是1211,一次类推,求第N次出现的字符串。主要是N次循环,每次循环找到数字出现的字数,然后保存在string中。用到一个数字转化成字符串函数,sprintf(s,”%d”,124354)
class Solution {
public:
string countAndSay(int n) {
string result = "1";
string str="";
char strcount[100];
if (n==1)
return result;
for(int i=2; i<=n; i++)
{
str="";
int len = result.length();
int count = 0;
char tmp = result[0];
for(int j=0; j<len; j++)
{
if (tmp == result[j])
{
count++;
}
else
{
sprintf(strcount,"%d",count);
str = str + strcount + tmp;
count = 0;
tmp = result[j];
j--;
}
}
sprintf(strcount,"%d",count);
str = str + strcount + tmp;
result = str;
}
return str;
}
};