请教大家求 k 位的水仙花数如何求,要求算法尽量优化
  public static boolean isArmstrongNumber(int n) {
        //...
    }
    public static int[] armstrongNumber(int k) {
        //...
    }
    public static BigInteger[] getArmstrongNumbers(){
        //...
    }
   其中public static boolean isArmstrongNumber(int n)已经实现,接下来public static int[] armstrongNumber(int k)是传入数字k ,就是数的位数为k为,如k=4的话,就要找出1000到9999之间的所有水仙花数,放入数组中,并返回。如k=5的话,就要找出10000到99999之间的所有水仙花数
   现在我就想请教,如何用优化的算法来实现这些方法?
  

解决方案 »

  1.   


    public class Test {
    private static final int[] arr = {0,1,8,27,64,125,216,343,512,729};
    public static void main(String[] args) { 
    System.out.println(isArmstrongNumber(153));


    public static boolean isArmstrongNumber(int n) { 
    int temp = n;
    while(temp!=0) {
    n -= arr[temp%10];
    temp/=10;
    }
    return n==0;

    }  
      

  2.   


    public class T {
    public static void main(String[] args) {
    int i, j, k, n;
    System.out.println("'water flower'number is:");
    for (n = 100; n < 1000; n++) {
    i = n / 100;
    j = n / 10 % 10;
    k = n % 10;
    if (i * 100 + j * 10 + k == i * i * i + j * j * j + k * k * k)
    System.out.println(n);
    }
    }
    }
      

  3.   

    我想下面的这个函数可以解决兄弟你的问题
    public int[] armstrongNumber(int k){
    int min=Math.pow(10,k-1);
    int max=Math.pow(10,k)-1;
    int j,m,sum;
    int temp[]=new int[k];
    for(int i=min;i<max;i++){
    m=i;
    sum=0;
    for(j=0;j<k;j++){
    temp[j]=m%10;
    sum+=Math.pow(temp[j],j+1);
    m/=10;
    }
    if(i==sum)
    System.out.println(i);
    }
    }
      

  4.   

    楼上的
    for(j=0;j <k;j++){ 
    temp[j]=m%10; 
    sum+=Math.pow(temp[j],j+1); 
    m/=10; 

    if(i==sum) 
    System.out.println(i); 
    好像判断的不对吧?
      

  5.   

    http://blog.csdn.net/zhw952/article/details/6719985
      

  6.   

    小弟的学习了,我的麻烦多了
          for(n=100;n<1000;n++)
    {
    h=n/100;
    i=n/10-h*10;
    j=n%10;
    if(n==h*h*h+i*i*i+j*j*j)
    System.out.print(n+"\t");