#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;
}

 

posted @ 2019-03-26 18:10  maitianpt  阅读(309)  评论(0编辑  收藏  举报