Visualize

Pattern visualizer

Reverse Bits

You never need to compute a destination index. n AND 1 hands you the lowest remaining bit, and result * 2 + bit pushes that bit onto the low end of the answer — so the FIRST bit taken gets shoved left once by every bit that follows it, landing at the far end. Taking bits low-to-high while writing them low-to-high is exactly what reverses the word. Animated on: n = 43 (binary 00101011) — reverse the order of its bits. Shown over 8 bits so the whole word fits on screen; LeetCode asks for 32, with the identical loop..

Peel off the low bit, push it onto the high end

time O(WIDTH) = O(32)space O(1)step 1 / 10
0
[0]
0
[1]
1
[2]
0
[3]
1
[4]
0
[5]
1
[6]
1
[7]
line 1

n = 43 is 00101011 across 8 bits. Reversing means the bit at position i (counting from the right) has to end up at position 7-i — every bit mirrors across the middle.

Pseudocode
1FUNCTION reverseBits(n, WIDTH):
2 result <- 0
3 FOR i <- 0 TO WIDTH - 1:
4 bit <- n AND 1
5 result <- result * 2 + bit
6 SHIFT n RIGHT BY 1
7 RETURN result

← / → step · space play · Home restart

Where to practice Bit Manipulation