easyBit ManipulationArrays & Hashing

Reverse Bits

easyTime: O(1)Space: O(1)

Recognize the pattern

reverse all bits of a 32-bit integerbit-by-bit extractionbuild reversed number

Brute force idea

A straightforward first read of Reverse Bits is this: Convert to binary string, reverse, convert back — but involves string operations. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The deeper shift in Reverse Bits is this: Loop 32 times: extract the last bit of n (n & 1), shift result left and add the bit, shift n right. Pure bit operations, no string conversion. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Key invariant

At the center of Reverse Bits is one steady idea: Each iteration moves one bit from the input's LSB to the result's growing MSB side. After 32 iterations, all bits are reversed. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Watch out for

The trap in Reverse Bits usually looks like this: Stopping early when n becomes 0 — you must always process all 32 bits, even if the remaining bits are 0, because those zeros become leading bits in the reversed result. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Arrays & Hashing Pattern