如果你有二进制数 10110,我怎样才能让它返回 5?例如,一个数字表示使用了多少位?下面列出了一些类似的例子:
- 101 应该返回 3
- 000000011 应该返回 2
- 11100 应该返回 5
- 101010101 应该返回 9
在 Java 中如何获得最简单的方法?我想出了以下方法,但我可以更快地完成吗:
public static int getBitLength(int value)
{
if (value == 0)
{
return 0;
}
int l = 1;
if (value >>> 16 > 0) { value >>= 16; l += 16; }
if (value >>> 8 > 0) { value >>= 8; l += 8; }
if (value >>> 4 > 0) { value >>= 4; l += 4; }
if (value >>> 2 > 0) { value >>= 2; l += 2; }
if (value >>> 1 > 0) { value >>= 1; l += 1; }
return l;
}
最佳答案
最简单?
32 - Integer.numberOfLeadingZeros(value)
如果您正在寻找算法,Java API 的实现者会同意您的分而治之的移位方法:
public static int numberOfLeadingZeros(int i) {
if (i == 0)
return 32;
int n = 1;
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
n -= i >>> 31;
return n;
}
编辑:提醒那些相信浮点计算准确性的人,运行以下测试工具:
public static void main(String[] args) {
for (int i = 0; i < 64; i++) {
long x = 1L << i;
check(x);
check(x-1);
}
}
static void check(long x) {
int correct = 64 - Long.numberOfLeadingZeros(x);
int floated = (int) (1 + Math.floor(Math.log(x) / Math.log(2)));
if (floated != correct) {
System.out.println(Long.toString(x, 16) + " " + correct + " " + floated);
}
}
第一个检测到的偏差是:
ffffffffffff 48 49
关于java - 计算 int 中使用的位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2935793/