当前位置: 移动技术网 > IT编程>开发语言>C/C++ > #leetcode刷题之路38-报数

#leetcode刷题之路38-报数

2019年03月27日  | 移动技术网IT编程  | 我要评论

社旗吧,猎场第9集,水泥胶砂振动台

报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 被读作 "one 1" ("一个一") , 即 11。
11 被读作 "two 1s" ("两个一"), 即 21。
21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。
注意:整数顺序将表示为一个字符串。
示例 1:
输入: 1
输出: "1"
示例 2:
输入: 4
输出: "1211"

#include <iostream>
using  namespace std;

string countandsay(int n) {
    string ans="1";
    int count;
    char temp1;
    string temp2;
    for(int j=0;j<n-1;j++)//n的值控制循环了几次
    {
        temp2=ans;
        ans="";//每次都要把ans重新置空
        int t=temp2.length();
        for(int i=0;i<t;i++)
        {
            count=1;
            temp1=temp2[i];
            while(i+1<temp2.length()&&temp2[i]==temp2[i+1])//记录后面有多少相同的
            {
                count++;
                i++;
            }
            ans+=to_string(count)+temp1;//更新ans
        }
    }
    return ans;
}

int main() {
    std::cout << countandsay(1)<<endl << countandsay(2)<<endl<< countandsay(3)<<endl<< countandsay(4)<<endl<< countandsay(5)<<endl<< std::endl;
    return 0;
}

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网