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依次求解n - 1次即可,但是当n > 8的时候,结果值将溢出。因此,必须用string来存储这些中间结果。
class Solution {
public:
string countAndSay(int n) {
string str;
if(n < 1)
return str;
for(int i = 0; i < n; i++)
{
if(i == 0)
{
str = "1";
continue;
}
int count = 0;
string nextstr;
int pos = 0;
while(pos < str.length())
{
char a = str[pos];
if(pos > 0 && a != str[pos - 1])
{
nextstr.append(1, '0' + count);
nextstr.append(1, str[pos - 1]);
count = 1;
}
else
count++;
pos++;
}
nextstr.append(1, '0' + count);
nextstr.append(1, str[pos - 1]);
str = nextstr;
}
return str;
}
};