【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)

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