Saturday, September 2, 2017

191. Number of 1 Bits

https://leetcode.com/problems/number-of-1-bits/description/
Solution 1. One operation of n&(n-1) eliminates the rightmost 1 of the integer. (3 ms)
int hammingWeight(uint32_t n)
{
    int res = 0;
    while(n)
    {
        n &= n - 1;
        ++ res;
    }
    return res;
}
Solution 2. shift and count 6 ms
    int hammingWeight(uint32_t n) {
        int res = 0;
        while(n) {
            res += (n&1);
            n >>= 1;
        }
        return res;
    }

No comments:

Post a Comment