sagelearnai

Number of 1 Bits

Difficulty: Easy · Pattern: Bit Manipulation · LeetCode #191

Return the number of 1 bits in the binary representation of a non-negative integer n (its Hamming weight, or popcount).

Examples

text
n = 11 (1011₂)          →  3
n = 128 (10000000₂)     →  1
n = 2147483645          →  30

Hints

  1. You could test each of the 32 bits.
  2. Faster: n & (n − 1) removes exactly the lowest set bit. How many times can you do that before n becomes 0?

Approach

Brian Kernighan's trick: repeat n &= n − 1 until n == 0, counting iterations. Each step clears one set bit, so the loop runs once per 1-bit rather than once per bit position. (Python 3.10+ also has int.bit_count().)

Complexity

Time: O(number of set bits) ≤ O(32). Space: O(1).

Python solution
def hammingWeight(n):
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count
JavaScript solution
function hammingWeight(n) {
  let count = 0;
  while (n !== 0) { n = (n & (n - 1)) >>> 0; count++; }
  return count;
}