easyBit ManipulationArrays & Hashing

Reverse Bits

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

Signals to notice

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

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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