1. 程式人生 > 其它 >java-判斷一個數是不是水仙花數

java-判斷一個數是不是水仙花數

// 水仙花數是指一個大於等於三位的數,它具備特徵:每一位的水仙花數的長度次冪之和等於水仙花數
//三位的水仙花數共有4個:153,370,371,407;
//四位的四葉玫瑰數共有3個:1634,8208,9474;
//五位的五角星數共有3個:54748,92727,93084;
//六位的六合數只有1個:548834;
public class Work9 {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int num = scanner.nextInt();
    int [] each_bit = get_each_bit(num);

    int sum = 0;
    for (int i = 0; i < each_bit.length; i++) {
        double pow = Math.pow(each_bit[i], each_bit.length);
        sum += pow;
    }
    if (sum == num){
        switch (each_bit.length) {
            case 3 -> System.out.println("這個數是水仙花數");
            case 4 -> System.out.println("這個數是四葉玫瑰數");
            case 5 -> System.out.println("這個數是五角星數");
            case 6 -> System.out.println("這個數是六合數");
            case 7 -> System.out.println("這個數是北斗七星數");
            case 8 -> System.out.println("這個數是八仙數");
            case 9 -> System.out.println("這個數是九九重陽數");
            case 10 -> System.out.println("這個數是十全十美數");
        }
    } else {System.out.println("這個數不是水仙花數");}
    scanner.close();
}
public static int[] get_each_bit(int num){
    int l = (num+"").length();
    int [] list = new int[l];
    int i = 0;
    while (num!=0){
        list[i] = num % 10;     // get last bit
        num = num / 10;   // delete num last bit
        i++;
    }
    return list;
}

}