Problem Statement
Reverse Bits
A computer stores a number as a row of 32 light switches, each one either off (0) or on (1). That row is called the number's bits, and bit just means one of those on/off switches. Here we are given a 32 bit unsigned integer (unsigned means it is never negative, so all 32 switches stand for value, none of them stand for a minus sign). The job is to reverse the row: take the bit that was on the far right and move it to the far left, take the second from the right and put it second from the left, and so on, until the whole row is flipped end to end. The trick we use is to read the original number one bit at a time from the right, and build the answer one bit at a time from the right, so the order naturally comes out backwards.
Signals to notice
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.
Trace it on n = 1 (00000000000000000000000000000001)
start: result=0, n=...0001 i=0: n&1=1 -> result=(0<<1)|1=1; n>>=1 -> n=0 i=1: n&1=0 -> result=(1<<1)|0=2; n=0 (stays 0) i=2: n&1=0 -> result=(2<<1)|0=4; n=0 ... i=3..30: each appends a 0, result doubles -> 8,16,...,1073741824 i=31: n&1=0 -> result=(1073741824<<1)|0=2147483648; n=0 all 32 bits processed -> return result = 2147483648
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.
Shape of the loop
result = 0
repeat 32 times:
result = (result << 1) | (n & 1) # pull n's LSB onto result's low end
n = n >> 1 # drop the bit we just took
return resultPseudocode only — the full worked solution lives in the Solution tab.
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.