zoukankan      html  css  js  c++  java
  • PAT 1140 Look-and-say Sequence [比较]

    1140 Look-and-say Sequence (20 分)

    Look-and-say sequence is a sequence of integers as the following:

    D, D1, D111, D113, D11231, D112213111, ...
    

    where D is in [0, 9] except 1. The (n+1)st number is a kind of description of the nth number. For example, the 2nd number means that there is one D in the 1st number, and hence it is D1; the 2nd number consists of one D (corresponding to D1) and one 1 (corresponding to 11), therefore the 3rd number is D111; or since the 4th number is D113, it consists of one D, two 1's, and one 3, so the next number must be D11231. This definition works for D = 1 as well. Now you are supposed to calculate the Nth number in a look-and-say sequence of a given digit D.

    Input Specification:

    Each input file contains one test case, which gives D (in [0, 9]) and a positive integer N (≤ 40), separated by a space.

    Output Specification:

    Print in a line the Nth number in a look-and-say sequence of D.

    Sample Input:

    1 8
    

    Sample Output:

    1123123111

     题目大意:描述序列,每一个序列都是描述前一个序列的。要求给出第n个序列。

    //本来一看差点懵了,但是告诉自己这个我肯定会做,然后就写出来啦,就是简单地找规律而已。

    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include<string.h>
    #include<string>
    #include<cstdio>
    using namespace std;
    
    string get(int c){//将计数转换为字符串
        string s;
        while(c!=0){
            s+=(c%10+'0');
            c/=10;
        }
        reverse(s.begin(),s.end());
        return s;
    }
    int main()
    {
        string s1,s2;
        int n;
        cin>>s1>>n;
        //s1=s1+"1";
        for(int i=1;i<n;i++){
            int ct=1;
            for(int j=0;j<s1.size();j++){
                while(s1[j]==s1[j+1]&&j<s1.size()-1){
                    ct++;j++;
                }
                s2+=s1[j]+get(ct);
                ct=1;//这里ct要转化为字符串。
            }
            s1=s2;
            s2="";
        }
        cout<<s1;
    
        return 0;
    }

    1.一开始直接用ct+'0'出现了乱码的情况,然后就简单地写了一个函数,转换为字符串,况且对于ct>10的那种也没法通过+‘0’直接转换了

    2.后来提交有一个测试点过不去,后来思考发现是因为自己一开始一进来就把s1+“1”,这样是不对的。修改了一下就可以了。

  • 相关阅读:
    如何进入高效学习状态
    shell printf命令:格式化输出语句
    C# virtual、abstract
    git解决Could not execute editor
    go defer笔记
    git从其他分支提取文件merge到当前分支
    golang map
    状态模式
    golang单例模式
    go 单元测试时读取配置文件
  • 原文地址:https://www.cnblogs.com/BlueBlueSea/p/9959663.html
Copyright © 2011-2022 走看看