杭电oj —— 2010

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());
			}
			
		}
	}

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值