java - 大于 lg N 的最小整数

标签 java algorithm math bit-manipulation

我在某处读到:

The smallest integer larger than lg N is the number of bits required to represent N in binary, in the same way that the smallest integer larger than log10 N is the number of digits required to represent N in decimal.

The Java statement

for (lgN = 0; N > 0; lgN++, N /= 2) ; 

is a simple way to compute the smallest integer larger than lg N

我可能在这里遗漏了一些东西,但是 Java 语句如何计算大于 lg N 的最小整数?

最佳答案

如果改写成while循环可能会更清楚:

lgN = 0
while( N > 0 ) {
    lgN++;
    N = N/2;
}

这可以被认为是“在我们移掉所有 1 之前我们必须右移多少次”(留下一个零)

关于java - 大于 lg N 的最小整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3935138/

相关文章:

algorithm - 选择幂集的随机元素

java - 在迭代时修改 Java ArrayList

Java 彩票数组程序

java - 当 “parent” 表具有复合 PK 时,如何在 JPA 中建模一对多关系?

java - 无法在 JavaFX 中加载 Controller

c# - 高度并行化的Levenshtein距离算法

algorithm - 我怎样才能在我的 matlab 脚本中拦截这个近似错误?

math - 从昂贵的搜索到整数规划或约束规划?

c++ - 在另一个文本中搜索长度超过 14 个字符的匹配子字符串的高效算法

c - 欧拉 160 : Find the non trivial 5 digits of the factorial