import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
public class HDU_OJ2010 {
/*
* 春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的:
* “水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如:153=1^3+5^3+3^3。 现在要求输出所有在m和n范围内的水仙花数。
*/
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
while (sn.hasNext()) {
//m n 均为三位数 前提条件:100<=m<=n<=999
int m = sn.nextInt();
int n = sn.nextInt();
int arr[] = new int[n-m];
int count = 0;
// Queue<Integer> priorityQueue = new PriorityQueue<Integer>(); 优先队列
for (int i = m; i <= n; i++) { //突然发现按照 i 的值进行验证操作,本身就是从小到大的顺序
/*
* 法一:
int b = i; //不能直接修改i的值
while(b != 0) {
int a = b % 10; //取到最后一位
ans += Math.pow(a,3);
b = b / 10; //变成了含前两位的两位数
}
*/
//法二:
int a = i/100; //百位
int b = i/10%10; //十位
int c = i%10; //个位
if((Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c,3)) == i)
arr[count++] = i;
}
if(count == 0) {
System.out.println("no");
} else {
//之前wrong answer的原因应该就是优先级队列的问题
for(int i = 0;i < count-1; i++) {
System.out.print(arr[i]+" ");
}
System.out.println(arr[count-1]);
}
}
}
}
priorityQueue也是可以使用的,一定要事先保存size(),我之前就犯了这一弱错。
优先级队列是一种建立最小堆的操作,通过二叉小顶堆实现,用一棵完全二叉树表示。
详情参考:https://www.cnblogs.com/CarpenterLee/p/5488070.html
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
public class HDU_oj2010_1 {
/*
* 春天是鲜花的季节,水仙花就是其中最迷人的代表,数学上有个水仙花数,他是这样定义的:
* “水仙花数”是指一个三位数,它的各位数字的立方和等于其本身,比如:153=1^3+5^3+3^3。 现在要求输出所有在m和n范围内的水仙花数。
*/
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
while (sn.hasNext()) {
//m n 均为三位数 前提条件:100<=m<=n<=999
int m = sn.nextInt();
int n = sn.nextInt();
Queue<Integer> priorityQueue = new PriorityQueue<Integer>(); //优先队列
for (int i = m; i <= n; i++) { //突然发现按照 i 的值进行验证操作,本身就是从小到大的顺序
int a = i/100; //百位
int b = i/10%10; //十位
int c = i%10; //个位
if((Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c,3)) == i)
priorityQueue.add(i);
}
int size = priorityQueue.size();
if(size == 0) {
System.out.println("no");
} else {
for(int i = 0;i < size-1; i++) {
System.out.print(priorityQueue.poll()+" ");
}
System.out.println(priorityQueue.poll());
}
}
}
}