打印所有的水仙花数

 1 package com.demo;
 2 
 3 /*
 4  * 题目:输出所有的水仙花数
 5  * 
 6  * 所谓水仙花数是指一个3位数,其各个位上数字的立方和等于其本身。
 7  * 例如: 153 = 1 * 1 * 1 + 3 * 3 * 3 + 5 * 5 * 5
 8  * 
 9  */
10 
11 public class NarcissisticNumber {
12     public static void main(String[] args) {
13 
14         for (int i = 100; i < 1000; i++) {
15             int n1 = i % 10; // 个位
16             int n2 = i / 10 % 10; // 十位
17             int n3 = i / 100; // 百位
18 
19             // 如果是水仙花数,则输出
20             if (i == n1 * n1 * n1 + n2 * n2 * n2 + n3 * n3 * n3) {
21                 System.out.println(i);
22             }
23         }
24 
25     }
26 }

运行结果:

153
370
371
407

猜你喜欢

转载自www.cnblogs.com/stefaniee/p/10908327.html