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.
#include<iostream>
#include<string>
using std::string;
using std::cout;
using std::endl;
class Solution
{
public:
string countAndSay(int n)
{
string strCountFor, strCountLat;
char chPoint;
int nCount, nStringLenFor, nStringLenLat;
for (int nTemp = 0; nTemp < n; nTemp++)
{
nCount = 1;
strCountLat = "";
if (nTemp == 0)
{
strCountLat = '1';
nStringLenLat = 1;
}
else
{
chPoint = strCountFor[0];
nStringLenLat = 0;
for (int nIndex = 0; nIndex < nStringLenFor; nIndex++)
{
if (nIndex == nStringLenFor - 1)
{
strCountLat += (nCount + '0');
strCountLat += chPoint;
nStringLenLat += 2;
break;
}
if ((chPoint != strCountFor[nIndex + 1]))
{
strCountLat += (nCount + '0');
strCountLat += chPoint;
nStringLenLat += 2;
nCount = 1;
chPoint = strCountFor[nIndex + 1];
}
else
{
nCount++;
}
}
}
strCountFor = strCountLat;
nStringLenFor = nStringLenLat;
}
return strCountLat;
}
};
int main()
{
int n = 6;
string strResult;
Solution SoFunction;
strResult = SoFunction.countAndSay(n);
cout << strResult << endl;
system("pause");
}