【两次过】Lintcode 365. 二进制中有多少个1

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

计算在一个 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?


解题思路:

最容易想到的方法是对数字依次右移,判断每一位是否为1,时间复杂度为o(n),n为数字有效位数,但是这个方法不够简洁。

更优的方法是使用n&(n-1),时间复杂度是o(m),m为1的位数,

具体实现原理可假设一个数为

num = 00010 10000

关注点放在后5位,

num-1 = 0001001111,可观察到,对一个数进行-1操作,会使最后一位1变0,高于最后一位1的位不变,低于最后一位1的位全变1,于是我们可以通过与操作,使原来最后一位1所在位变成0。并通过这个方法来判断总共有多少个1

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

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/82313797
今日推荐