【Lintcode】1332. Number of 1 Bits

題目地址:

https://www.lintcode.com/problem/number-of-1-bits/description

給定一個數nn,求其二進制表示中11的個數。可以用lowbit解決。其中lowbit(x) = x & -x,指的是x的二進制表示最右邊的1所代表的十進制數是幾。這可以由-x = ~x + 1得到。代碼如下:

public class Solution {
    /**
     * @param n: an unsigned integer
     * @return: the number of ’1' bits
     */
    public int hammingWeight(int n) {
        // write your code here
        int res = 0;
        while (n != 0) {
            res++;
            n -= lowbit(n);
        }
        
        return res;
    }
    
    private int lowbit(int x) {
        return x & -x;
    }
}

時間複雜度O(logn)O(\log n),空間O(1)O(1)

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