Reverse Bits
EasyNeetCode 150Top Interview 150 Bit ManipulationProblem
Given a 32-bit integer n, reverse the order of its 32 bits: the lowest bit becomes the highest,
the second lowest becomes the second highest, and so on. Return the new number.
The original problem treats n as an unsigned 32-bit value. Here every input and output is shown as an
ordinary non-negative int below 231, so Python, Java and C++ agree. That needs bit 31 of
n to be 0 and also bit 0 to be 0, because those two swap places.
Constraints
- 0 ≤ n < 2^31 and n is even (bit 0 is 0), so that both n and the answer are shown as non-negative ints
- The number is always read as exactly 32 bits, with leading zeros
Examples: pick one to animate
Solutions
TimeO(1)
SpaceO(1)
Time: The loop always runs exactly 32 times.
Space: Two integers, x and result.
Peel the lowest bit off x and push it onto the end of result, 32 times. The first bit taken gets pushed left by every later round until it reaches bit 31, so the order comes out reversed.