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
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.
1FUNCTION reverseBits(n, WIDTH):2 result <- 03 FOR i <- 0 TO WIDTH - 1:4 bit <- n AND 15 result <- result * 2 + bit6 SHIFT n RIGHT BY 17 RETURN result
← / → step · space play · Home restart