以下是Java代码示例,用于打印出所有的水仙花数:

public class NarcissisticNumber {
    public static void main(String[] args) {
        for (int i = 100; i <= 999; i++) {
            int hundreds = i / 100; // 获取百位数
            int tens = (i / 10) % 10; // 获取十位数
            int units = i % 10; // 获取个位数

            int sum = (int) (Math.pow(hundreds, 3) + Math.pow(tens, 3) + Math.pow(units, 3));

            if (sum == i) {
                System.out.println(i);
            }
        }
    }
}

运行以上代码,将会输出所有的水仙花数:

153
370
371
407

这些数满足条件:各位数字立方和等于该数本身。


原文地址: http://www.cveoy.top/t/topic/i4A3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录