Interger 类中有方法 bitCount
方法解释:
Returns the number of one-bits in the two’s complement binary representation of the specified int value. This function is sometimes referred to as the population count.
Parameters:
i the value whose bits are to be counted
Returns:
the number of one-bits in the two’s complement binary representation of the specified int value.
简单的说:
返回给定int值的二进制表示中 1 的个数
如果要求一个是 2的幂 的int值中,其二进制表示时 1 所在的位置(从低位算起)。
可以通过如下方法:
int num; // 假定其为2的幂
int pos = Integer.bitCount(num - 1) + 1; // 求位置
// 对于一个2的幂数的二进制表示来说
// 其减去1后,1所在位置之后就全为1
// 因而bitCount会直接返回之前的 1 所在的位置-1的值,再加 1 即为之前位置
/*
比如 4
二进制表示 0000 0100
减1
二进制表示 0000 0011
求bitCount,得2,再加1,得3
*/