两个数组的幂(n)

我的代码不起作用


public static int[] powersOfTwoArray(int n) {

    int[] result = new int[n];

    int i = 0;

    int power = 0;

    while (i <= n) {

        result[i] = power;

        power *= 2;

    }

    return result;

}

该方法应返回一个包含 2 从 2 raise 到 0 的幂的数组。


jeck猫
浏览 99回答 2
2回答

互换的青春

您的代码存在三个问题,我在代码中提到了它们:public static int[] powersOfTwoArray(int n)&nbsp;{&nbsp; &nbsp; int[] result = new int[n+1];&nbsp; // use "n+1" otherwise it will throw exception&nbsp; &nbsp; int i = 0;&nbsp; &nbsp; int power = 1;&nbsp; &nbsp;// initiate power = 1, not power = 0;&nbsp; &nbsp; while (i <= n)&nbsp;&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; result[i] = power;&nbsp; &nbsp; &nbsp; &nbsp; power *= 2;&nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; // increments "i" otherwise its an infinite loop&nbsp; &nbsp; }&nbsp; &nbsp; return result;}

FFIVE

您正在与零相乘,每次都等于零。尝试int&nbsp;power&nbsp;=&nbsp;1;如果我误解了,请说明您的问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java