Number of 1 Bits

给个整数, 数一. 因为是Integer,所以一共32位. 1 << i 就是每个位上的1.

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