191. Number of 1 Bits - jiejackyzhang/leetcode-note GitHub Wiki

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

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

一个思路是一位一位的检查是否为1。 令mask=1,将n与mask做AND位运算,再将mask左移一位,repeat。

另一种思路是找到最右边的1,将它变为0,同时res++。repeat直到n变为0。 n & (n-1)恰好可以完成这个操作。

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 & (n-1); 
        }
        return res;
    }
}