Brian Kernighan's bit counting trick.
def hammingWeight(n): count = 0 while n: n &= (n - 1) count += 1 return count
time where k is set bits, space.
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
The approach
Brian Kernighan's bit counting trick.
def hammingWeight(n): count = 0 while n: n &= (n - 1) count += 1 return count
time where k is set bits, space.