打印出所有的 水仙花数 ,所谓水仙花数是指一个三位数,其各位数字立方和等于该数本身。例如:153 是一个水仙花数 ,因为 153 = 1 的三次方 +5 的三次方 +3 的三次方
在 100–999 范围内,共有 4 个 水仙花数:
153
371
407
370是一个 三位数
满足:百位³ + 十位³ + 个位³ = 原数
例如:
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 位阿姆斯特朗数,因为
三位数中只有上述 4 个满足条件。