191. Number of 1 Bits

Question

Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Algorithm

A similar question to the question 338. Counting bits. Use n&n-1 to count the non zero bit from least significant bit.

Code

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int res = 0;
        while (n != 0) {
            res++;
            n &= n-1;
        }
        return res;
    }
}