Dotcpp  /  试卷列表  /  Java  /  题目 8027

验证水仙花树(水仙花数是指一个3位数,它的每个位上的数

验证水仙花树(水仙花数是指一个3位数,它的每个位上的数字的3次幂之和等于它本身)

答案
import java.util.Scanner;

public class NarcissisticNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入一个三位数:");
        int num = sc.nextInt();

        // 校验输入必须是三位数
        if(num < 100 || num > 999){
            System.out.println("输入数字不是三位数");
            return;
        }

        // 拆分百位、十位、个位
        int hundred = num / 100;
        int ten = num / 10 % 10;
        int unit = num % 10;

        // 计算各位数字三次方之和
        int sum = hundred*hundred*hundred + ten*ten*ten + unit*unit*unit;

        // 判断并输出结果
        if(sum == num){
            System.out.println(num + " 是水仙花数");
        }else{
            System.out.println(num + " 不是水仙花数");
        }
        sc.close();
    }
}

题目信息

题号:8027
题型:简答题
知识点:Java
难度:普通