计算长数中设置位的数量

Counting number of set bits in a long number

此问题已得到解答

我的问题是,遵循方法 1 是可行的,但是它的变体,即方法 2 不起作用,而是它提供了预期输出值的两倍。我找不到原因。

方法一

public class Solution {
    public int numSetBits(long a) {
        int count = 0;
        long temp = 0;
        for(int i = 0 ; i < 64 ; i++) { // 64-bit for long data-type
            temp = 1;
            temp = temp << i;
            temp = a & temp;
            if((temp > 0))
                count++;
        }
      return count;
    }
}

方法 2

public class Solution {
    public int numSetBits(long a) {
        int count=0;
        for(int i=0; i<64; i++) {
            if((a & (1 << i))>0) count++;
        }
      return count;
    }
}

第二种方法失败,因为 1 << i 的结果是 int,而不是 long。所以位掩码环绕,因此 a 的低 32 位被扫描两次,而 a 的高 32 位未被计算。

所以,当i达到值32时,(1 << i)将不是232,而是20(即1),这与i为0时相同。同样,当i为33时,(1 << i)不会是233, 但 21, ...等等

通过使常量 1 成为 long:

来更正此问题
(1L << i)