/* 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. */ class Solution { public: string int2string(int c) { string cstr; while (c) { cstr += (char)(c % 10 + '0'); c = c / 10; } reverse(cstr.begin(), cstr.end()); return cstr; } string countAndSay(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function string ret = "1"; if (n <= 1) return ret; int i = 2; while (i <= n) { string tmp; int j = 0, count = 0; while (j < ret.size()) { char cur = ret[j]; int c = 1; ++j; while (j < ret.size() && ret[j] == ret[j - 1]) { ++j; ++c; } string&& cstr = int2string(c); tmp += cstr + cur; } ret = tmp; ++i; } } };