365. 二进制中有多少个1

提示

        LintCode中的相关算法题实现代码,可以在我的GitHub中下载。

题目需求

计算在一个 32 位的整数的二进制表示中有多少个 1.

样例

给定 32 (100000),返回 1

给定 5 (101),返回 2

给定 1023 (1111111111),返回 10

挑战

If the integer is n bits with m 1 bits. Can you do it in O(m) time?

解题思路

    可以根据位运算求解,n&(n-1),即可计算出一个bit

实现代码

class Solution {
public:
    /*
     * @param num: An integer
     * @return: An integer
     */
    int countOnes(int num) {
        // write your code here
        int times=0;
        while(num)
        {
            num=num&(num-1);
            times++;
        }
        return times;
    }
};

猜你喜欢

转载自blog.csdn.net/oeljeklaus/article/details/80653184