二进制中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;>>:右移,高位补符号位;

posted @ 2017-05-22 20:05  雪浪snowWave  阅读(194)  评论(0编辑  收藏  举报