问题
水仙花数定义:
- 一定是 3 位数
- 每一位的立方,加起来恰好是这个数本身,比如 153 = 1x1x1 + 5x5x5 + 3x3x3
寻找所有的水仙花数
解答
public class NarcissisticNumber
{
public static void main (String[] args)
{
find();
}
public static void find ()
{
for (int high = 1; high <= 9; high++)
{
for (int middle = 0; middle <= 9; middle++)
{
for (int low = 0; low <= 9; low++)
{
int t = thisNum(high, middle, low);
if ( t == sumOfnum3(high, middle, low) )
{
System.out.println( t );
}
}
}
}
}
public static int thisNum (int high, int middle, int low)
{
return high*100 + middle*10 + low;
}
public static int sumOfnum3 (int high, int middle, int low)
{
return num3(high) + num3(middle) + num3(low);
}
public static int num3 (int num)
{
return num * num * num;
}
}