计蒜客 难题题库 023 计数和数数

来源:互联网 发布:阿里云架构师 编辑:程序博客网 时间:2024/05/03 07:55

“伯爵说”序列如下:1, 11, 21, 1211, 111221, ...1 读作 "one 1" 或者 11。11 读作 "two 1s" 或者21。21 读作 "one 2, one 1" 或者 1211。

格式:多组输入,读到文件结束。每组输入给定一个整数n,输出第n个序列。(1<=n<=30)

注意:整数序列以字符串的形式表示。

PS:相信你已经看懂了题目,如果没看懂,小提示下,

其实类似于求”菲波拉契“数列的第n项哦~

样例1

输入:

6

输出:

312211


#include<iostream>#include<string>#include<algorithm>using namespace std;string numToStr(int n){    if(n == 0){        return "0";    }    string res;    while(n){        res.push_back(n % 10 + '0');        n /= 10;    }    reverse(res.begin(), res.end());    return res;}string  bole(string s){    string res;    char last_char = s[0];    int count = 1;    int len = s.length();    for(int i = 1; i < len; ++i){        if(s[i] != last_char){            res += numToStr(count) + last_char;            last_char = s[i];            count = 1;        }else{            count++;        }    }    res += numToStr(count) + last_char;    return res;}int main(){    int n;    while(cin >> n){        string s = "1";        while(--n){            s = bole(s);        }        cout << s << endl;    }}


0 0
原创粉丝点击