源本科技 | 码上会

水仙花数

2026/01/26
26
0

题目

打印出所有的 水仙花数 ,所谓水仙花数是指一个三位数,其各位数字立方和等于该数本身。例如:153 是一个水仙花数 ,因为 153 = 1 的三次方 +5 的三次方 +3 的三次方

运行示例

在 100–999 范围内,共有 4 个 水仙花数:

153
371
407
370
👈点击左箭头查看答案(一定要在自己思考并实现后再看参考答案哦!)

什么是水仙花数?

  • 是一个 三位数

  • 满足:百位³ + 十位³ + 个位³ = 原数

  • 例如:153=13+53+33=1+125+27=153153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153

public class NarcissisticNumber {
    public static void main(String[] args) {
        System.out.println("所有的水仙花数为:");
        for (int num = 100; num <= 999; num++) {
            if (isNarcissistic(num)) {
                System.out.println(num);
            }
        }
    }

    /**
     * 判断一个三位数是否为水仙花数
     */
    public static boolean isNarcissistic(int num) {
        int hundreds = num / 100;           // 百位
        int tens = (num % 100) / 10;        // 十位
        int units = num % 10;               // 个位

        int sumOfCubes = hundreds * hundreds * hundreds
                       + tens * tens * tens
                       + units * units * units;

        return sumOfCubes == num;
    }
}

补充知识

  • 水仙花数是“n 位阿姆斯特朗数”的特例(n=3)

  • n 位阿姆斯特朗数定义:各位数字的 n 次幂之和等于该数本身

    • 例如:9474 是 4 位阿姆斯特朗数,因为

    • 94+44+74+44=6561+256+2401+256=94749^4 + 4^4 + 7^4 + 4^4 = 6561 + 256 + 2401 + 256 = 9474

  • 三位数中只有上述 4 个满足条件。