二进制中1的个数

题目:给你一个int型的整数,返回它二进制中1的个数,注意可能给负数

思路:用无符号右移可以解决负数的情况,while循环的条件要变成不等于0

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

 注:>>>:无符号右移,高位补0;>>:右移,高位补符号位;

原文地址:https://www.cnblogs.com/team42/p/6891140.html