Question:
Definition of the number of daffodils:
- Must be 3 digits
- The cube of each digit adds up to exactly the number itself, such as
153=1*1*1+5*5*5+3*3*3
Find all the daffodil numbers
Problem-solving ideas:
Because the definition indicates that the number of daffodils must be three digits, we make a loop from 100 to 999:
for(int i=100;i<1000;i++)
Then you need to get each digit of this three-digit number
Take 153 as an example:
Single digit: Take the remainder of 10 to get the single digit. 153/10=15……3, namely get the ones place: 3
Tens digit: The tens digit is a little more complicated. First divide by 10, eliminate the ones digit, and get the two digit 15, then take the remainder of the two digits to get the single digit, 15%10=1...5 to get the tens digit : 5
Hundreds digit: The hundreds digit is relatively simple. Divide directly by 100 to get the hundreds digit: 153/100=1
Then calculate the three numbers obtained, and then determine whether it is equal to the number itself. Regarding the cube, you can use it Math.pow(x,3)
, or it can be x*x*x
simple and crude.
Complete code:
public class Main {
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
int gw = i % 10; //获得个位数
int sw = (i / 10) % 10; //获得十位数
int bw = i / 100; //获得百位数
if (gw * gw * gw + sw * sw * sw + bw * bw * bw == i)
System.out.println(i); //输出符合条件的水仙花数
}
}
}