← Bit Manipulation

Drill #86 — Reverse bits

Easy Bit Shift Bit Manipulation

In plain English: Flip the binary representation of a 32-bit number so the first bit becomes the last and vice versa.

Extract the lowest bit of n, place it at the correct reversed position in the result by shifting left, then shift n right. Repeat 32 times.

Prompt

Reverse the bits of a 32-bit unsigned integer.

Try to write it from scratch before scrolling down.

Solution

def reverse_bits(n):
    result = 0
    for _ in range(32):
        result = (result << 1) | (n & 1)  # shift result left, add lowest bit of n
        n >>= 1
    return result

# Test: reverse_bits(0b00000010100101000001111010011100) == 964176192
# Test: reverse_bits(0) == 0
O(1) time (32 iterations) ยท O(1) space

Related Micro Drills

← Drill #85 Drill #87 →