【C++】数数:用数字来数数Count and Say

题目:The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.
刚拿到题目的时候我也是蒙蔽的不知道题目啥意思,要是想不出来大家不要觉得自己的智商不够啊。其实题目的意思是,“用数字表达上一个数”。比如上一个数是“1211”,出现了1个1,1个2,以及2个1,所以输出就是“111221”。理解题目了下面就好办了。
本题目要用到一点递归的思想,代码如下:

//将数字转换成字符串
string int2string(int x){
    ostringstream stream;
    stream<<x;
    string k = stream.str();
    return k;
}
//将字符串的数字用数字“数”出来
string getStr(string numStr){
    int i=0,j=1,counts=1;
    string result="";
    for(;j<numStr.length();++i,++j){
        if(numStr[i]!=numStr[j]){
            result +=int2string(counts)+numStr[i];
            counts=1;
            continue;
        }
        else
            counts++;
    }
    result +=int2string(counts)+numStr[i];
    return result;
}
//给出n时,输出第n个数数。主调函数。
string countAndSay(int n) {
    if(n==1)
        return "1";
    string preString = countAndSay(n-1);
    return getStr(preString);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一杯拿铁go

你的打赏是我更新最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值