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