找到了,找到了,用 Integer.bitCount 这个方法可了,它就是引自《高效程序的奥秘》一书中的算法, JDK 中的源代码如下: public static int bitCount(int i) { // HD, Figure 5-2 i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; }
重新做一次...public class Test { public static void main(String[] args) { System.out.println(countBit(20)); }
嘿嘿,找到个更妖的...public class Test { public static void main(String[] args) { int leftZeroCount = Integer.numberOfLeadingZeros(20); System.out.println(32 - leftZeroCount); } }Integer.numberOfLeadingZeros 统计最左边 1 前面 0 的个数, 源代码(也是从那本书里弄来的,反正我是没看懂)如下, public static int numberOfLeadingZeros(int i) { // HD, Figure 5-6 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; }
JDK 中的源代码如下: public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
System.out.println(countBit(20));
}
private static int countBit(int num) {
if(num == 0) {
return 0;
}
if(num < 0) {
return Integer.SIZE;
}
int count = Integer.SIZE;
while((num >>> 31) == 0) {
num <<= 1;
count--;
}
return count;
}
}
int count = 0;
while (input != 0) {
input = input >>> 1;
count++;
}
System.out.println(count);
int leftZeroCount = Integer.numberOfLeadingZeros(20);
System.out.println(32 - leftZeroCount);
}
}Integer.numberOfLeadingZeros 统计最左边 1 前面 0 的个数,
源代码(也是从那本书里弄来的,反正我是没看懂)如下, public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
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;
}