Number of 1 Bits - Implementation

Here is the implementation:

function hammingWeight(n):
    count = 0
    while n != 0:
        n = n & (n - 1)
        count += 1
    return count

This runs in O(k)O(k) time where kk is the number of set bits. Worst case is O(logn)O(\log n) for 32/64 bit integers.