第一题
小明只喜欢数字 2, 3, 5这三个数字,如222,333,235这样的。但是12345这样就不是他喜欢的,因为包含了除了2,3,5以外的数字。
现询问这个人喜欢的第n个数字(升序排列的第n个数字)是多少。 n <= 1000;
思路:首先把递归树一画就知道这是一个bfs,但是做的时候一直卡在怎么换位上,下面就是参考大佬的代码,加上了我自己的理解。
import java.awt.print.Pageable;
import java.util.*;
/**
* @author VX5
* @Title: MJC
* @ProjectName examination
* @Description: TODO
* @date ${DAT}19:23
*/
public class JD01 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=input.nextInt();
long result=getResult(n);
System.out.print(result);
}
static int[] nums={2,3,5};
static List<Long> queue = new LinkedList<>();
public static long getResult(int n){
if (n <= 0){
return -1;
}else if (n == 1){
return 2;
}else if (n == 2){
return 3;
}else if (n == 3){
return 5;
}
n -= 3;
queue.add(2L);
queue.add(3L);
queue.add(5L);
while (!queue.isEmpty() && n > 0){
int size = queue.size();// 当前位数有多少个数字
for (int i = 0; i < nums.length; i++){// 这相当于一个广度遍历 这个循环开始是以2、3、5开头的数
// 循环一遍没有出结果后 就说`在这里插入代码片`明位数会多一位,那么这个时候就要从队列中删除上一个size的元素
// 比如我这个循环第一次执行的时候加入了 22 23 25 32 33 35 52 53 55 那么这个跳出循环后就要将 2 3 5这之前的三个数删除队列 以便末尾加三个数的循环直接从22开始加
long num = nums[i];
for (int j = 0; j < size; j++){// 末尾加3个数的循环
long item = Long.valueOf(num + "" + queue.get(j));
n--;
if (n == 0){
return item;
}
queue.add(item);
}
}
for (int i = 0; i < size; i++){// 出队列
queue.remove(0);
}
}
return -1;
}
}