如何用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 hundreds = 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");
}
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:70
阅读量:89
阅读量:84
阅读量:51
阅读量:30