【发布时间】:2016-07-28 20:53:33
【问题描述】:
当我使用 n = 64 运行此方法时,它给了我 x = 64,但不是运行 if 语句,而是运行 else 语句。实际答案需要是 32,但它返回 64。
/**
* Complete the method to find the largest power of 2 less than the given number
* Use a loop
*/
public class MathUtil {
public int largestPowerOf2(int n) {
// TODO: implement this method.
int i = 0;
while(n > 1) {
n = n / 2;
i ++;
}
System.out.printf("i = %d\n" , i);
int x = (int)Math.pow(2,i);
System.out.println(x);
if(x == n) {
return (int)Math.pow(2,i - 1);
} else {
return (int)Math.pow(2, i);
}
}
}
【问题讨论】:
-
这听起来是一个让您熟悉调试器使用的好机会。在代码执行时单步执行并检查运行时值和行为。
-
提示:执行if语句时
n有什么值?当您回答了这个问题后,您就会知道代码为什么不起作用。干杯:) -
当您在 while 循环中连续执行
n = n / 2;时,您认为if(x == n)将如何执行? -
你的算法在这里是错误的。它在整数已经是 2 的幂的情况下不起作用。这是一个边界问题。您需要在逻辑中更好地处理该边界。
-
您在寻找
Integer.highestOneBit(n - 1)吗?