java算法–水仙花數
題目:打印出所有的 “水仙花數 “
- 分析:利用 for 循環控制 100-999 個數,每個數分解出個位,十位,百位。
/**
* 找出100-999之間的水仙花數
* 水仙花數是指一個 3 位正整數,它的每個位上的數字的 3 次冪之和等於它本身。
* 例如:1^3 + 5^3+ 3^3 = 153
* @author Rain_JN
* @data 2017年6月5日
* @version V1.0
*/
public class FindNums{
public static void main(String[] args){
MyMath math = new MyMath();
for(int i = 100; i < 999; i++){
if(math.isNarcissisticNumber(i)){
System.out.println(i);
}
}
}
}
class MyMath{
/**
* 判斷一個3位數是否爲水仙花數
* @param x 要判斷的數
* @return 如果是,返回true,否則返回false
*/
public boolean isNarcissisticNumber(int x){
int unit=0, decade=0, hundred=0;
// 一個n位整數x
// 個位 = x / 1 % 10,十位 = x / 10 % 10, 百位 = x / 100 % 10, ... , n位 = x / n % 10
unit = x % 10;
decade = x / 10 % 10;
hundred = x / 100 % 10;
if(x == (unit*unit*unit + decade*decade*decade + hundred*hundred*hundred)){
return true;
}
return false;
}
}