首页 > 其他 > 详细

报数count-and-say

时间:2015-12-03 02:03:43      阅读:417      评论:0      收藏:0      [点我收藏+]

报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:

1, 11, 21, 1211, 111221, ...

1 读作 "one 1" -> 11.

11 读作 "two 1s" -> 21.

21 读作 "one 2, then one 1" -> 1211.

给定一个整数 n, 返回 第 n 个顺序。

样例

给定 n = 5, 返回 "111221".

注意

整数的顺序将表示为一个字符串。

解题思路:不断地循环递归即可。第n个数字相当于在第n-1个的每一个数字前面加上个数的过程。

 1 public class Solution {
 2     /**
 3      * @param n the nth
 4      * @return the nth sequence
 5      */
 6     public String countAndSaymethod(String input){
 7         char temp = input.charAt(0);
 8         int num = 1;
 9         StringBuffer newString = new StringBuffer("");
10         for(int i=1;i<input.length();i++){
11             if(input.charAt(i)==temp){
12                 num++;
13                 continue;
14             }
15             newString.append(Integer.toString(num)+temp);
16             temp = input.charAt(i);
17             num = 1;
18         }
19         newString.append(Integer.toString(num) + temp);  
20         return newString.toString(); 
21     }
22     public String countAndSay(int n) {
23         // Write your code here
24         String result = "1";
25         int i = 1;
26         while(i<n){
27             result = countAndSaymethod(result);
28             i++;
29         }
30         return result;
31     }
32 }

 

报数count-and-say

原文:http://www.cnblogs.com/wangnanabuaa/p/5014876.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!