38 Count and Say

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.

class Solution {
public:
    string countAndSay(int n) {
        string res;
        if ( n == 0 ) { res = ""; return res;}
        if ( n == 1 ) { res = "1"; return res;}
        string tmp_res = countAndSay(n-1);
        int i = 0, nres = tmp_res.size(), icount; 
        while ( i <= nres-1 ) {
            char c = tmp_res[i];
            icount = 0;
            while ( i <= nres-1 and tmp_res[i] == c ) {
                icount += 1;
                i += 1;
            }
            res += to_string(icount);
            res += c;
        }
        return res;
    }
};

Note: cast an integer to a string

string s = to_string(integer);

results matching ""

    No results matching ""