BiruLyu
5/25/2017 - 9:49 PM

191. Number of 1 Bits.java

/*In the following solution:

Iterate over 32 bits since its a 32-bit integer. This will be O(1) since it is in constant time
Left shift the number by i to get the LSB value
Do an AND of the number obtained from step 2 with 1. If the result of the AND is 1 then increment the count because the LSB value of that bit was 1.
*/ 
 public int hammingWeight(int n) {
        int count = 0;
        for(int i=0; i<32; i++){
            count += (n >> i & 1) == 1 ? 1: 0;
        }
        return count;
    }
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        while(n != 0){
            n = n & (n-1);
            count++;
        }
        return count;
    }
}