
第一种方法是将n不断与2的i次方相与,如果n的2的i次方的位置上是1,相与的结果就是1,res++,最后返回res即可。
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;
    }
}第二种方法就是利用一个小窍门,n&(n-1)会把n最低位的1变成0,比如6&(6-1)=4。6=110,4=100其实就是把6二进制的最低位的1翻转为0,所以我们可以不断让n和n-1相与,直到n变成0,运算的次数就是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){
            n &= n-1;
            res++;
        }
        return res;
    }
}


















