剑指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;
}

 

posted @ 2018-08-06 19:18  liter7  阅读(98)  评论(0编辑  收藏  举报