Reverse bits of a given 32-bit unsigned integer and return the result as an unsigned integer.
Output: 964176192 (binary: 00111001011110000010100101000000)
Explanation: The input's binary bits reversed gives the output.
Output: 3221225471 (binary: 10111111111111111111111111111111)
Iterate 32 times. In each iteration, extract the lowest bit of n and shift it into the correct position in the result. Shift n right by 1 after each step.
- Initialize result to 0.
- For each of the 32 bit positions: left-shift result by 1, then OR with the current lowest bit of n.
- Right-shift n by 1 to move to the next bit.
- After 32 iterations, result holds the reversed bits.
Complexity Analysis:
Time complexity: O(1) — always 32 iterations regardless of input.
Space complexity: O(1) — constant extra space.