The count-and-say sequence is the sequence of integers with the first five terms as following:
- 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 term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
class Solution {
public:
string countAndSay(int n) {
if(0==n) return string("0");
string str1("1");
for(int i = 2; i <= n; ++i){ // iters
// every iter
string str2("");
int pos = 0;
while(pos < str1.size() ){
char c = str1[pos];
int count = 1;
while(pos + count < str1.size() && str1[pos + count]== c) ++count;
str2 += (to_string(count) + str1[pos]);
// (char)(count-'0') 会比 to_string(count)快,但是怎么限定10个以内,还是一定在10以内?
pos += count;
}
str1.swap(str2);
}
return str1;
}
};