如何用Java判断水仙花数
的有关信息介绍如下:
水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。
(例如:1^3 + 5^3+ 3^3 = 153)
首先,要了解什么是水仙花数,这样才能快速选择是用什么方式、方法,甚至算法来解决问题。
水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。
(例如:1^3 + 5^3+ 3^3 = 153)
创建工程,或使用已有工程,在工程下创建包,包内新建一个类,我命名为Narcissistic类,大家根据自己喜好随便命名,但请保持类名与文件名一致。
先写一个函数计算一个数字的立方为多少。我命名为cube()
private static int cube(int n) {
return n * n * n;
}
判断这个数是不是水仙花数,求每一位数上的数的立方和是否为原数字本身。
private static Boolean isNarcissistic(int number) {
int hundreds = number / 100;
int tens = number / 10 - hundreds * 10;
int ones = number % 10;
return cube(hundreds) + cube(tens) + cube(ones) == number;
}
写一个for循环来判断那些数字是水仙花数,并输出。
for (int index = 100; index < 1000; ++index) {
if (isNarcissistic(index))
System.out.print(index + "\t");
}



