我需要找到小于给定数字的 2 的最大幂。
我卡住了,找不到任何解决方案。
代码:
public class MathPow {
public int largestPowerOf2 (int n) {
int res = 2;
while (res < n) {
res =(int) Math.pow(res, 2);
}
return res;
}
}
这不能正常工作。
测试输出:
Arguments Actual Expected
-------------------------
9 16 8
100 256 64
1000 65536 512
64 256 32
如何解决这个问题?
最佳答案
Integer.highestOneBit(n-1);
对于 n <= 1
这个问题真的没有意义。在该范围内做什么留给感兴趣的读者。
在 Hacker's Delight 中有一个很好的位旋转算法集合.
关于java - 如何找到小于给定数的2的最大次方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17379020/