Problem03 水仙花数

题目:打印出所有的"水仙花数"。"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。

   例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。

程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

 1 public class Problem03 {
 2     //打印所有三位水仙花数
 3     //水仙花数:是指一个三位数,其各位数字立方和等于该数本身
 4     public static void main(String args[]) {
 5         int b=0,s=0,g=0;
 6         for(int i=100; i<1000; i++) {
 7             //获取百位,十位,个位分别记为b,s,g
 8             b = i/100;
 9             s = (i/10)%10;
10             g = i%10;
11             if(b*b*b+s*s*s+g*g*g==i) {
12                 System.out.print(i+" ");
13             }
14         }
15     }
16 }

输出结果:

1 153 370 371 407 

猜你喜欢

转载自www.cnblogs.com/nemowang1996/p/10387685.html