如何在不使用Math
的情况下执行二进制对数?
现在我有了这个 Math.log(x)/Math.log(2)
并且它可以工作,但我无法使用 java.lang.Math
。
我能做什么?
int bits_necessaris = (int)(log2(nat + 1)); // This is correct
// The function where I'm having trouble
public static int log2(int x) {
return (something);
}
重要:当我执行 Math.log(7)/Math.log(2)
时,我得到 2.80XXXXX
所以我这样做了:
(int) Math.ceil(Math.log(7) / Math.log(2));
我得到ceil(2.80XXXXX) = 3
。
函数的返回值必须向上舍入,例如,如果解为 6.777,则返回值必须为 7。
最佳答案
您想知道表示一个 int 需要多少位?然后还有更简单的解决方案,例如:
int bitsNeededFor(int i) {
int bits = 0;
while (i > 0) {
bits++;
i /= 2;
}
return bits;
}
再想一想,以下内容更快、更容易理解:
int bitsNeededFor(int i) {
return 32 - Integer.numberOfLeadingZeros(i);
}
关于java - 没有 java.lang.Math 的二进制对数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22312492/