DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

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
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

Open interactive visualization

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


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

Top comments (0)