整體思路:循環拿這個數對10取余,再除以10,判斷是不是0
while (num > 0) {
int v = num%10;
num /= 10;
}
案例:
* 需求:在控制台輸出所有的”水仙花數”
* 所謂的水仙花數是指一個三位數,其各位數字的立方和等於該數本身。
* 舉例:153就是一個水仙花數。
* 153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153
public static void main(String[] args) {
int countAll = 0;
// 水仙花數
for(int i=100; i<1000; i++) {
int num = i; //數值
int result = 0; //各個位三次方相加后的數值
while (num > 0) {
int v = num%10;
result += v*v*v;
num /= 10;
}
if (result == i) {
countAll ++;
System.out.println("第"+countAll+"個水仙花數為:"+result);
}
}
}
//結果:
//第1個水仙花數為:153
//第2個水仙花數為:370
//第3個水仙花數為:371
//第4個水仙花數為:407
