Java实现水仙花数概述与实现

	    g:在控制台打印水仙花数
		h:统计水仙花个数
	需求:在控制台输出所有的”水仙花数”
	
	分析:
		我们都不知道什么叫"水仙花数",你让我怎么做呢?
		
		所谓的水仙花数是指一个三位数,其各位数字的立方和等于该数本身。
		举例:153就是一个水仙花数。
		153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153

		A:三位数其实是告诉了我们范围。
		B:通过for循环我们就可以实现获取每一个三位数
		  但是麻烦是如何获取这个三位数的个,十,百位上的数据
		  
		  我们如何获取一个数据的个,十,百呢?
			假设有个一个数据:153
			ge:	153%10 = 3
			shi: 153/10%10 = 5
			bai:153/10/10%10 = 1
			qian:x/10/10/10%10
			wan:  x/10/10/10/10%10
			...

		C:让ge*ge*ge+shi*shi*shi+bai*bai*bai和该数据比较
		  如果相同,就把该数据在控制台输出。

使用for循环:

public class  水仙花数 {

	public static void main(String[] args) {
	
		//for循环版本
				int count = 0;
				
				for(int x=100; x<1000; x++) {
					int ge = x%10;
					int shi = x/10%10;
					int bai = x/10/10%10;
					
					if((ge*ge*ge+shi*shi*shi+bai*bai*bai) == x) {
						count++;
						System.out.println(x);
					}
				}
				
				System.out.println("count:"+count);
			
				
		}
}

使用while循环:

    public class 水仙花数 {
	public static void main(String[] args) {
	//while循环版本
				int count2 = 0;
				int y = 100;
				while(y<1000) {
					int ge = y%10;
					int shi = y/10%10;
					int bai = y/10/10%10;
					
	              if((ge*ge*ge+shi*shi*shi+bai*bai*bai) == y) {
						count2++;
						System.out.println(y);
					}
					
					y++;
				}
				
				System.out.println("count2:"+count2);
			}
	}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值