Here is the implementation:
function hammingWeight(n):
count = 0
while n != 0:
n = n & (n - 1)
count += 1
return count
This runs in time where is the number of set bits. Worst case is for 32/64 bit integers.
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
Here is the implementation:
function hammingWeight(n):
count = 0
while n != 0:
n = n & (n - 1)
count += 1
return count
This runs in time where is the number of set bits. Worst case is for 32/64 bit integers.