剑指offer 14. 二进制中1的个数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaohaibo_/article/details/85806558

输入一个整数,输出该数二进制表示中1的个数。

例如,将9表示为二进制是1001,有2位是1,因此,如果输入为9,输出应当为2。

样例

输入:9
输出:2

这道题需要考虑负数,负数为补码

法1:

class Solution {
public:
    int NumberOf1(int n) {
        int ans = 0;
        for(int i = 0; i < 32; i ++)
            if(n >> i & 1) ans ++;
        return ans;
    }
};

法2:

class Solution {
    public int NumberOf1(int n)
    {
        int ans = 0;
        while(n)
        {
            n -= n & -n;
            ans ++;
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/zhaohaibo_/article/details/85806558