Java 之 水仙花数

题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。 

1.程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。

 编程实现:

import java.util.*;

public class DaffodilTest{

  public static void main(String args[]){

    int hundred = 0;

    int ten = 0;

    int bit = 0;

    for(int i=100; i<=999; i++){

      hundred = i/100; //分解出百位

      ten = i%100/10; //分解出十位

      bit = i%10; //分解出个位

      if(Math.pow(hundred,3)+Math.pow(ten,3)+Math.pow(bit,3) == i){

        System.out.println("100~999 水仙花数:"+i);

      }

    }

  }

}

 

解法二:

public class DaffodilTest{

  public static void main(String args[]){

    for(int hundred=1; hundred<=9; hundred++){

      for(int ten=0; ten<=9; ten++){

        for(int bit=0; bit<=9; bit++){

          if((100*hundred+10*ten+bit) == (hundred*hundred*hundred+ten*ten*ten+bit*bit*bit)){

            System.out.println("100~999 水仙花数:"+hundred+ten+bit);

          }

        }

      }

    }

  }

}

posted @ 2012-01-25 15:58  qin520  阅读(350)  评论(0编辑  收藏  举报