public static void main(String[] args) {
// 找出0-999999所有水仙花数
/*
水仙花数是指一个 3 位数,它的每个位上的数字的 3次幂之和等于它本身。例如:1^3 + 5^3+ 3^3
= 153。
*/
/*
两个步骤
1 找出每一位上的数字
2 判断数字有几位
*/
for(int i = 0; i <= 999999; i++) {
int count = 0; //记录数字位数
int tmp = i;
//153为例
/*
153 != 0, count++得1 153/10 = 15
15 != 0, count++得2 15/10 = 1
1 != 0, count++得3 1/10 = 0
循环终止 count为3
*/
while(tmp != 0) {
count++;
tmp = tmp / 10;
}
tmp = i;
int sum = 0;
while(tmp != 0) {
sum += Math.pow(tmp % 10, 3);
tmp = tmp /10;
}
if( sum == i) {
System.out.println(i+"是水仙花数");
}
}
}
寻找水仙花数(代码加注释)
最新推荐文章于 2024-01-28 20:22:34 发布