File: reverse-bits/solution.py

Date: 2026-06-06

Time: 18:52

reverse-bits/solution.py

Purpose

This file implements LeetCode #190 — Reverse Bits. It provides a single function that takes a 32-bit unsigned integer and returns the integer formed by reversing its binary representation. For example, 0b00000010100101000001111010011100 becomes 0b00111001011110000010100101000000.

Key Components

reverse_bits(n: int) -> int — The sole public function. Contract: accepts a 32-bit unsigned integer (0 to 2^32 - 1), returns a 32-bit unsigned integer with all 32 bits reversed.

Flow

The algorithm builds the result one bit at a time across exactly 32 iterations:

1. Extract: n & 1 isolates the least significant bit of n.

2. Place: result << 1 shifts the accumulator left to make room, then | (n & 1) appends the extracted bit at position 0.

3. Advance: n >>= 1 drops the consumed bit from n.

After 32 iterations, the first bit extracted (originally bit 0 of n) sits at bit 31 of result, and the last bit extracted (originally bit 31) sits at bit 0. This is the classic iterative bit-reversal idiom.

Patterns

Dependencies

Imports: None — pure arithmetic, no standard library usage.

Imported by: The reverse-bits/testsolution.py file. The massive "Imported By" list in the prompt is misleading — those are test files for *other* problems that likely share a common test harness or import pattern, not actual consumers of reversebits.

Invariants

Error Handling

None. The function assumes valid input per the LeetCode contract (unsigned 32-bit integer). No bounds checking, no type validation. This is typical for competitive programming solutions.

Topics to Explore

Beliefs