Counting number of set bits in a long number

十年热恋 提交于 2020-02-03 08:26:08

问题


This question has been answered here.

My query is, following approach-1 works, however the variation of it, that is approach-2 does not, rather it gives double the value of expected output. I can not find out why.

Approach-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;
    }
}

Approach-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:


The second approach fails because the result of 1 << i is an int, not a long. So the bit mask wraps around, and so the lower 32 bits of a get scanned twice, while the higher 32 bits of a are left uncounted.

So, when i reaches the value 32, (1 << i) will not be 232, but 20 (i.e. 1), which is the same as when i was 0. Similarly when i is 33, (1 << i) will not be 233, but 21, ...etc.

Correct this by making the constant 1 a long:

(1L << i)


来源:https://stackoverflow.com/questions/59991296/counting-number-of-set-bits-in-a-long-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!