File: number-of-1-bits/solution.py

Date: 2026-06-06

Time: 18:14

number-of-1-bits/solution.py

Purpose

This file implements LeetCode problem #191 "Number of 1 Bits" (also known as the Hamming weight problem). It provides a single function that counts set bits in a 32-bit unsigned integer. Despite being scoped to one problem, the "Imported By" list shows it's referenced by hundreds of test files across the repo — likely because the test harness uses a shared import pattern, not because other solutions call hamming_weight directly.

Key Components

hamming_weight(n: int) -> int — The sole export. Takes an integer, returns the count of 1 bits in its binary representation.

Patterns

The implementation uses Brian Kernighan's bit-clearing algorithm rather than the naive approach of shifting and checking each bit. The key insight is the expression n &= n - 1, which clears the lowest set bit in each iteration.

How it works for n = 12 (binary 1100):

1. n - 1 = 1011. n & (n-1) = 1000. count = 1.

2. n - 1 = 0111. n & (n-1) = 0000. count = 2.

3. n is 0, loop exits. Return 2.

This is strictly better than a 32-iteration shift-and-mask loop: it iterates exactly *k* times where *k* is the number of set bits. For sparse inputs (few 1s), it terminates much faster.

Dependencies

Imports: None — pure computation with no external dependencies.

Imported by: The massive "Imported By" list (300+ test files) is an artifact of the repo's test scaffolding structure, not an indication that other solutions depend on this function. The test runner or test template likely imports all solution modules uniformly.

Flow

1. Initialize count = 0.

2. While n is nonzero: clear the lowest set bit with n &= n - 1, increment count.

3. Return count.

The loop body is two operations per iteration with no branches, making it cache-friendly and branch-predictor-friendly.

Invariants

Error Handling

None. Negative inputs would cause an infinite loop in CPython (Python integers are arbitrary-width, so -1 & -2 is still negative), but the contract states the input is unsigned.

Topics to Explore

Beliefs