最简单?
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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)