Counting number of set bits in a long number

srs :

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;
    }
}
trincot :

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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=6103&siteId=1