1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

#include <string>
#include <iostream>
#include <sstream>

using namespace std;

string CountAndSay(string s)
{
    if (s.size() <= 0)return "";

    stringstream sout;
    int count = 1;
    char ch = s[0];
	
    for (size_t i = 1; i < s.size(); ++i)
    {
        if (s[i] == ch)
            ++count;
        else
        {
            sout << count << ch;
            count = 1;
            ch = s[i];
        }
    }

    sout << count << ch;
    return sout.str();
}

string CountAndSay(int n)
{
    string s = "1";

    while(--n > 0)
        s = CountAndSay(s);

    return s;
}

int main(int argc, char** argv)
{
    cout << CountAndSay(1) << '\n';
    cout << CountAndSay(5) << '\n';
    cout << CountAndSay(7) << '\n';
    return 0;
}
View Program Text


Test Status