java经典算法|水仙花数

问题描述

       打印出所有的 水仙花数 。所谓 水仙花数是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个 水仙花数 ,因为153 = 1^3 + 5^3+ 3^3

问题分析

       由于水仙花数是一个三位数,故范围是101~1000,判断每个数的立方之和是否等于该数本身,分别取出该数的个位(%10)、十位(/10%10)、百位(%100),如果是水仙花数则打印输出。

代码实现

public class DaffodilsNumber {
    
    

    public static void main(String[] args) {
    
    
        int x, y, z;
        for (int i = 101; i < 1000; i++) {
    
    
            x = i % 10;
            y = i / 10 % 10;
            z = i / 100;
            if (x * x * x + y * y * y + z * z * z == i)
                System.out.print(i + " ");
        }
        System.out.println();
    }
}

运行结果

水仙花数运行结果

猜你喜欢

转载自blog.csdn.net/ChaunceyLX/article/details/120156268