【Lintcode】365. Count 1 in Binary

题目地址:

https://www.lintcode.com/problem/count-1-in-binary/description

给定一个3232位整数,求其二进制表示中11的个数。可以用lowbit解决。其中lowbit(x) = x & -x,指的是x的二进制表示最右边的1所代表的十进制数是几。这可以由-x = ~x + 1得到。代码如下:

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

时间复杂度O(logn)O(\log n),空间O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章