java算法--水仙花数

java算法–水仙花数


题目:打印出所有的 “水仙花数 “

  • 分析:利用 for 循环控制 100-999 个数,每个数分解出个位,十位,百位。

/**
 * 找出100-999之间的水仙花数
 * 水仙花数是指一个 3 位正整数,它的每个位上的数字的 3 次幂之和等于它本身。
 * 例如:1^3 + 5^3+ 3^3 = 153
 * @author Rain_JN
 * @data 2017年6月5日
 * @version V1.0
 */
public class FindNums{
    public static void main(String[] args){
        MyMath math = new MyMath();
        for(int i = 100; i < 999; i++){
            if(math.isNarcissisticNumber(i)){
                System.out.println(i);
            }
        }
    }
}

class MyMath{
    /**
     * 判断一个3位数是否为水仙花数
     * @param x 要判断的数
     * @return 如果是,返回true,否则返回false
     */
    public boolean isNarcissisticNumber(int x){
        int unit=0, decade=0, hundred=0;
        // 一个n位整数x
        // 个位 = x / 1 % 10,十位 = x / 10 % 10, 百位 = x / 100 % 10, ... , n位 = x / n % 10
        unit = x % 10;
        decade = x / 10 % 10;
        hundred = x / 100 % 10;
        if(x == (unit*unit*unit + decade*decade*decade + hundred*hundred*hundred)){
            return true;
        }
        return false;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值