报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:
1. 1
2. 11
3. 21
4. 1211
5. 111221
示例 1:
1
1
示例 2:
4
1211
输出结果是字符串。
规律为:
当前结果读上一个结果,中间有一样的数字就一起读。例如:
11读的是上一个1,1个1,所以结果为11.
21读的是上一个11,2个1,所以结果为21.
1211读的是上一个21,1个2和1个1,所以结果为1211.
以此类推。
每一个结果读的都是上一个结果,所以用递归。
import java.util.Scanner;
public class Number {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
int s = sc.nextInt();
System.out.println(countnumber(s));
}
}
public static String countnumber(int n) {
if (n == 1)
return "1";
if (n == 0)
return "请输入大于0的数";
String str = countnumber(n - 1);
char[] c = str.toCharArray();
int count = 1;
int len = c.length;
StringBuffer s = new StringBuffer();
for (int i = 0; i < len; i++) {
if (i == len - 1) {
s.append("" + count + c[i]);
break;
}
if (c[i] == c[i + 1]) {
count++;
continue;
} else {
s.append("" + count + c[i]);
count = 1;
}
}
return s.toString();
}
}