zoukankan      html  css  js  c++  java
  • #leetcode刷题之路38-报数

    报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
    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;
    }
  • 相关阅读:
    Spring简介和基础
    el表达式
    Spring MVC 文件上传下载
    el表达式的function标签
    JSTL核心标签库使用
    基于注解的SpringMVC
    new一个Object对象占用多少内存?
    leetcode-第k个排列(Java和c++版)
    使用maven构建web项目(简易版)
    leetcode-电话号码的字母组合
  • 原文地址:https://www.cnblogs.com/biat/p/10601994.html
Copyright © 2011-2022 走看看