# The Bit Reverser

> Sometimes the answer is literally backwards.

Canonical URL: <https://datadriven.io/problems/the_bit_reverser>

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

Given a non-negative integer, reverse its 32-bit binary representation and return the resulting unsigned 32-bit integer.

## Worked solution and explanation

### Why this problem exists in real interviews

Reversing 32 bits of an integer tests **bitwise manipulation at a specific width**. It checks whether you can build a result bit by bit and understand the shift-and-accumulate pattern.

---

### Break down the requirements

#### Step 1: Extract the lowest bit of the input

Use `n & 1` to get the least significant bit.

#### Step 2: Shift the result left and add the extracted bit

Build the reversed number from the least significant bit upward.

#### Step 3: Shift the input right and repeat 32 times

Process all 32 bits regardless of the number's magnitude.

---

### The solution

**Bit-by-bit reversal across 32-bit width**

```python
def reverse_bits(n):
    result = 0
    for i in range(32):
        bit = n & 1
        result = (result << 1) | bit
        n >>= 1
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(1). Exactly 32 iterations regardless of input value.
> 
> **Space:** O(1). A single integer accumulator.

> **Interviewers Watch For**
>
> Processing exactly 32 bits, not stopping when n becomes 0. Leading zeros in the original become trailing ones in the reversed result.

> **Common Pitfall**
>
> Stopping the loop when `n == 0`. If the input is `1` (bit 0 set), the reversed 32-bit value has bit 31 set (2^31), not 1. You must process all 32 positions.

---

## Common follow-up questions

- Can you reverse bits in O(log n) operations using divide-and-conquer? _(Tests swapping halves progressively: swap 16-bit halves, then 8-bit, then 4-bit, then 2-bit, then 1-bit.)_
- What if the bit width is 64 instead of 32? _(Tests parameterizing the loop count.)_
- How does endianness relate to bit reversal? _(Tests understanding that endianness affects byte order, not bit order within a byte.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_bit_reverser)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.