题目:
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;
解法 :用循环 读出N个数
string countAndSay(int n)
{
if (n <=0)
cout << "n<=0,不合理" << endl;
if(n==1)
cout<<"1"<<endl;
//int count=0;
string results;
string say = "1";
//char last = say[0];
for (int i =1 ; i<n; i++)
{
string s;
char last = say[0];
int count=0;
for (size_t j = 0; j <say.size(); j++)
{
if ( say[j]==last )
{
count++;
}
else
{
s.push_back(count+'0');
s.push_back(last);
last = say[j];
count = 1;
}
}
s.push_back(count+'0');
s.push_back(last);
say=s;
}
return say;
}