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