剑指Offer(书):二进制中1的个数

题目:输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

分析:下面这两种方法都可以,不过第二种更好一些。

public int numberOf1(int n) {
    int count = 0;
    while (n != 0) {
        if ((n & 1) == 1) {
            count++;
        }
        n = n >>> 1;
    }
    return count;
}
public int numberOf12(int n) {
    int count = 0;
    while (n != 0) {
        count++;
        n &=(n-1);
    }
    return count;
}
原文地址:https://www.cnblogs.com/liter7/p/9432063.html