LeetCode 191 Number of 1 Bits - Implementation

The approach

Brian Kernighan's bit counting trick.

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

O(k)O(k) time where k is set bits, O(1)O(1) space.