LeetCode 190: Reverse Bits — Step-by-Step Visual Trace


Easy — Bit Manipulation | Math

The Problem

Given a 32-bit unsigned integer, reverse the bits and return the resulting integer.

Approach

Iterate through all 32 bits of the input number, extracting each bit from right to left using bitwise AND with 1, then building the reversed number by left-shifting and adding each extracted bit. Use right shift to process the next bit of the input.

Time: O(1) · Space: O(1)

Code

class Solution:
    def reverseBits(self, n: int) -> int:
        reversed_num = 0
        for _ in range(32):
            reversed_num = (reversed_num << 1) | (n & 1)
            n = n >> 1
        return reversed_num

Watch It Run

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.


Comments