Java基础编程题——水仙花数

时间:2022-07-26 21:43:45
 package com.yangzl.basic;
/**
* 题目:打印出所有的"水仙花数".
* 所谓"水仙花数"是指一个三位数,
* 其各位数字立方和等于该数本身。
* 例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。  
*
* @author Administrator
*
*/
/*程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。*/
public class ShuiXianHua {
public static void main(String[] args) {
for(int i=101;i<1000;i++){
if(isSXH(i)==true){
System.out.println(i+"为水仙花数");
}
}
}
/**
* 判断是否为水仙花的函数
* @return
*/
public static boolean isSXH(int n){
boolean bl = false;
//注意:n是100~1000之间的三位数
int x = n/100;//百位
int y = (n%100)/10;//十位
int z = n%10;//个位
if(n == (x*x*x + y*y*y + z*z*z)){
bl = true;
}
return bl;
}
}

结果:

153为水仙花数
370为水仙花数
371为水仙花数
407为水仙花数