leetcode-38-count and sway

Problem Description:

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.

题目大意:

边数边说出上一次的结果。 1读作 “1 1”,11读作“ 2 1”,21读作“1 2 1 1”

Solutions:

递归调用该函数,利用上一次的计算结果来读数即可。注意:数字转化成字符串的时候不可以直接 +’0’,因为有可能会是超过一位数。

Code in C++:

class Solution {
public:
    string countAndSay(int n) {
        if(n==0) return "";
        if(n==1) return "1";
        string res="";
        string prev = countAndSay(n-1);
        int count = 1;
        char cur=prev[0];
        for(int i = 1 ; i < prev.length(); i++)
        {
            if(prev[i]==cur) count++;
            else
            {
                res+=i2s(count);
                res+=cur;
                count = 1;
                cur=prev[i];
            }
        }
        res+=i2s(count);
        res+=cur;
        return res;

    }
    string i2s(int n)
    {
        string res = "";
        while(n>0){
            res+=(char)(n%10+'0');
            n/=10;
        }
        return res;
    }
};