小编srs*_*srs的帖子

计算长数中设置位的数量

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

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

java algorithm bit-manipulation

4
推荐指数
1
解决办法
70
查看次数

标签 统计

algorithm ×1

bit-manipulation ×1

java ×1