在Java中找到阿姆斯壮数字

时间:2018-10-04 19:51:11

标签: java

我找到了所有这些数字,但是我不明白为什么在我的代码中,循环的方向决定了一切 当他从9999升至100时,他不会计算小于1000的数字 当周期从100到9999时,一切都会从头到尾... 有效的代码:

public class Main {
    public static void main(String[] args){
        int n  , po = 0, count = 0;
        double arm;
        int[] elems = {0,0,0,0};
        for(int i = 100; i < 9999; i++){
            for( n = i;n >= 1; count++){
                elems[count] = n%10;
                n /= 10;
                po++;
            }
            arm = pow(elems[0],po)+pow(elems[1],po)+pow(elems[2],po)+pow(elems[3],po);
            if(arm == i ){
                System.out.println(i);
            }
            po = 0;
            count = 0;
        }
    }
}

输出:

153
370
371
407
1634
8208
9474

和无效的代码:

public class Main {
    public static void main(String[] args){
        int n  , po = 0, count = 0;
        double arm;
        int[] elems = {0,0,0,0};
        for(int i = 9999; i > 100; i--){
            for( n = i;n >= 1; count++){
                elems[count] = n%10;
                n /= 10;
                po++;
            }
            arm = pow(elems[0],po)+pow(elems[1],po)+pow(elems[2],po)+pow(elems[3],po);
            if(arm == i ){
                System.out.println(i);
            }
            po = 0;
            count = 0;
        }
    }
}

输出:

9474
8208
1634

如您所见,差异仅在于循环的方向...为什么会发生这种情况?

2 个答案:

答案 0 :(得分:3)

并非所有elems元素都被i < 1000覆盖,因此,在评估arm = pow(...时,先前的内容仍然保留。

还要为外部elems循环的每次迭代重置for

答案 1 :(得分:2)

添加:Arrays.fill(elems,0);

 public static void armstrong() {
    int n  , po = 0, count = 0;
    double arm;
    int[] elems = {0,0,0,0};
    for(int i = 9999; i > 100; i--){
        for( n = i;n >= 1; count++){
            elems[count] = n%10;
            n /= 10;
            po++;
        }
        arm = pow(elems[0],po)+pow(elems[1],po)+pow(elems[2],po)+pow(elems[3],po);

        if(arm == i ){
            System.out.println(i);
        }
        //added
        Arrays.fill(elems, 0);
        po = 0;
        count = 0;
    }

}