問題解析:
所謂水仙花數就是一個數等於組成該數各個位的立方和,例如370=3^3+7^3。由於計算量比較小,可以使用簡單的循環語句來完成。對於不同位數的數字,可以進行分段討論。
代碼實現:
package com.java.test;
public class Demo9 {
public static void main(String[] args) {
//計算0~9中的水仙花數
for (int i = 0; i < 10; i++) {
if(i == Math.pow(i, 3)) {
System.out.println(i + "是水仙花數");
}
}
//計算10~99中的水仙花數
for (int i = 10; i < 100; i++) {
int a = i/10; //獲得十位上的數字
int b = i%10; //獲得個位上的數字
if(i == (Math.pow(a, 3) + Math.pow(b, 3))) {
System.out.println(i + "是水仙花數");
}
}
//計算100~999中的水仙花數
for (int i = 100; i < 1000; i++) {
int a = i/100;
int b = i/10%10;
int c = i%10;
if(i == (Math.pow(a, 3) + Math.pow(b, 3) + Math.pow(c, 3))) {
System.out.println(i + "是水仙花數");
}
}
}
}