java算法--水仙花数

来源:互联网 发布:黑帽seo如何赚钱 编辑:程序博客网 时间:2024/05/23 17:46

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;    }}
原创粉丝点击