题目
打印出所有的 "水仙花数 ",所谓 "水仙花数 "是指一个三位数,其各位数字立方和等于该数本身。
实现方法一
//百位、十位、个位都是0-9之间的数字,三个循环嵌套,组合出一个三位数,注意百位有值,所以x从1开始
static void func1(){
for (int x = 1; x <= 9; x++) {
for (int y = 0; y <= 9; y++) {
for (int z = 0; z <= 9; z++) {
if (x * x * x + y * y * y + z * z * z == 100 * x + 10 * y + z) {
System.out.println(100 * x + 10 * y + z);
}
}
}
}
}
实现方法二
//先预设一个三位数,然后拆分出百位、十位、个位
static void func2(){
//先预设一个三位数,然后拆分出百位、十位、个位
for(int value = 100; value <= 999; value++){
int bai = value/100;
int shi = value/10%10;
int ge = value%10;
if(bai*bai*bai + shi*shi*shi + ge*ge*ge == value){
System.out.println(value);
}
}
}
实现方法三(网上找的,暂时没想通2020.9.15)
//先预设一个数字,然后呢?
static void func3(){
for(int i=2;i<=1000;i++){
int n = i;
int sum = 0;
while(n>0){
int t = n%10;
sum += t*t*t;
n = n/10;
}
if(i == sum){
System.out.println(i);
}
}
}
结果
153
370
371
407