Java 计算长数中的设置位数

Java 计算长数中的设置位数,java,algorithm,bit-manipulation,Java,Algorithm,Bit Manipulation,这个问题已经回答了 我的问题是,下面的方法1是有效的,但是它的变体,即方法2不是,而是它给出了预期输出的两倍值。我不知道为什么 方法1 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

这个问题已经回答了

我的问题是,下面的方法1是有效的,但是它的变体,即方法2不是,而是它给出了预期输出的两倍值。我不知道为什么

方法1

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;
    }
}
公共类解决方案{
公共整数位数(长a){
整数计数=0;
长期温度=0;
对于(int i=0;i<64;i++){//64位的长数据类型
温度=1;
温度=温度0)
计数++;
}
返回计数;
}
}
方法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;
    }
}
公共类解决方案{
公共整数位数(长a){
整数计数=0;

对于(int i=0;i第二种方法失败,因为
1的结果,如果你能详细解释的话,请特别说明:
位掩码的部分,因此a的低32位会被扫描两次,而a的高32位则没有计数
我添加了更多的文本来说明发生了什么。
(1L << i)