Number of 1 Bits – Solution & Complexity

Solution Walkthrough

  1. Step 1: Clear the lowest set bit with n & (n - 1)

    • Subtracting 1 from n flips the lowest 1 bit to 0 and all trailing 0s to 1.
    • Bitwise ANDing n & (n - 1) therefore clears exactly one set bit — the rightmost 1.
    • Repeating n = n & (n - 1) until n == 0 loops only as many times as there are set bits (Brian Kernighan's algorithm).
  2. Step 2: Optimal O(1) bit-clearing loop

    • Runs in O(k) iterations where k <= 31 is the number of set bits (O(1) time for fixed-width integers) and O(1) space.
    def hamming_weight(n: int) -> int:
        count = 0
        while n:
            n &= n - 1
            count += 1
        return count
  3. Step 3: Common mistakes

    • Using signed right shift >> on negative 32-bit integers in Java/JavaScript without >>> can cause an infinite loop if the sign bit is set.
    • Converting to a binary string works but allocates unnecessary memory compared to n &= n - 1.

FAQ