Reverse Bits
Reverse the 32 bits of an unsigned integer by shifting exactly 32 times regardless of how early the input runs out of set bits.
Open on LeetCode ↗Intuition
The tempting shortcut is to stop the loop once n hits zero, since there is nothing left to shift out. That is wrong: the leading zeros of the input are the trailing zeros of the output, and if you quit early the result never gets shifted into its final position. The loop has to run exactly 32 times no matter what n looks like. Each round takes the lowest bit of n, ORs it onto the bottom of a growing result after shifting that result left one place, then drops the lowest bit of n by shifting it right. Doing this the full 32 times guarantees every position, including the ones that were already zero, ends up where it belongs.
Approach
Loop exactly 32 times
Do not use a while condition tied to n being nonzero. Use a fixed range of 32 iterations, since a 32-bit integer always has 32 positions to place, even if most of them are zero.
Peel the lowest bit of n into result
On each iteration, shift result left by one to make room, then OR in n & 1, the current lowest bit of n. This builds the result from the bottom up, one bit per iteration, in reversed order relative to n.
Shift n right to expose the next bit
After extracting the lowest bit, shift n right by one so the next iteration sees the next bit. After 32 iterations every original bit position has been read once and placed into the mirrored position of result.
Solution & live demo
Edge cases
Every bit read is 0, so the loop still runs 32 times and correctly returns 0.
Those zero bits still get shifted into result at the correct low positions during the later iterations, which is exactly why the loop cannot exit early.
Treat n as unsigned throughout; in languages with signed shifts, mask with 0xFFFFFFFF after each left shift to avoid sign extension.
Result is also 0xFFFFFFFF since the bit pattern is a palindrome; the loop still runs the full 32 rounds.