计算长数中设置位的数量

srs*_*srs 4 java algorithm bit-manipulation

这个问题已经在这里回答。

我的查询是,遵循方法 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

方法二

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

tri*_*cot 5

第二种方法失败,因为 的结果1 << iint,而不是long。因此位掩码环绕,因此低 32 位a被扫描两次,而高 32 位a则不计入数。

因此,当i达到值 32 时,(1 << i)将不是 2 32,而是 2 0(即 1),这与i0 时相同。同样,当i是 33 时,(1 << i)将不是 2 33,而是 2 1等.

通过使常量 1 a 更正此问题long

(1L << i)
Run Code Online (Sandbox Code Playgroud)