我的代碼不起作用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 的冪的數組。
2 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
您的代碼存在三個問題,我在代碼中提到了它們:
public static int[] powersOfTwoArray(int n)
{
int[] result = new int[n+1]; // use "n+1" otherwise it will throw exception
int i = 0;
int power = 1; // initiate power = 1, not power = 0;
while (i <= n)
{
result[i] = power;
power *= 2;
i++; // increments "i" otherwise its an infinite loop
}
return result;
}
添加回答
舉報
0/150
提交
取消