我需要计算长整数中设置位的数量.另外,我需要优化相同.我正在使用以下代码:
I need to count number of set bits in a long number. Also I need to optimize the same. I'm using the following code:
public static int countSetBits(long number) { int count = 0; while (number > 0) { ++count; number &= number - 1; } return count; }任何修改将不胜感激.
推荐答案您可以按以下步骤编写而不加减法
You can write it without subtraction as follow
public static int countSetBits(long number) { int count = 0; while (number > 0) { count += number&1L; number>>=1L; } return count; }如果要使用Java的内置库,则可以使用 bitCount
If You want to use Java's built-in libraries then can use bitCount
Long.bitCount(number)如果您想查看源代码然后
public static int bitCount(long i) { i = i - ((i >>> 1) & 0x5555555555555555L); i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; i = i + (i >>> 8); i = i + (i >>> 16); i = i + (i >>> 32); return (int)i & 0x7f; }