计蒜客刷题之旅 之 计数和数数

本文介绍了一种生成伯爵说序列的算法实现,并通过C++代码详细展示了如何根据输入的整数n生成对应的序列。该序列从1开始,每个后续项由前一项的发音构成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

输入格式
多组输入,读到文件结束。每组输入给定一个整数 n(1 \leq n \leq 30)n(1≤n≤30)。

输出格式
输出第 nn 个序列。注意,整数序列以字符串的形式表示。

样例输入
6
样例输出
312211

题目难度:一星

#include <iostream>
using namespace std;

//整数转换为字符串函数
string toString(int a)
{
    string str = "";
    while(a){
        str = a%10 + '0';
        a /= 10;
    }
    return str;
}

int main()
{
    int n;
    //多组数据输入
    while(cin >> n){
        string count = "1";
        for(int i=1; i<n; i++){
            //创建临时string存储count的处理结果
            string count_tmp = "";
            char character = count[0];
            int cnt = 1;//连续相同字符的个数

            //逐个对count中的字符进行处理
            for(int j=1; j<count.length(); j++){
                //有连续相同字符则cnt加一
                if(count[j] == character)
                    cnt++;
                //否则计数归1,count的临时量存入处理数据
                else{
                    count_tmp += toString(cnt);
                    count_tmp += character;
                    cnt = 1;
                    character = count[j];
                }
            }
            //在临时量中存入最后一个连续字符的数据
            count_tmp += toString(cnt);
            count_tmp += character;
            count = count_tmp;
        }
        cout << count << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值