c/c++语言开发共享#leetcode刷题之路38-报数

报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:1. 12. 113. 214. 12115. 1112211 被读作 "one 1" ("一个一") , 即 11。11 被读作 "two 1s" ("两个一"), 即 21。21 被读作 "one 2", "one …

报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
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;  }

 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/604596.html

(0)
上一篇 2021年5月12日
下一篇 2021年5月12日

精彩推荐