InterviewPrepKit

Home / Coding / Bit Manipulation

Reverse Bits

easy Original β†—
Solving tips
  • Simple approach: pull the low bit of n and push it onto a left-shifting accumulator: result = (result << 1) | (n & 1), then n >>= 1, done exactly 32 times.
  • Loop a FIXED 32 times, not 'until n == 0', or leading zeros never get shifted into place and the result is too small.
  • Shift result BEFORE ORing in the new bit; ORing first corrupts the low bit.
  • Advanced O(log width) = 5-step method: swap adjacent bits, then 2-bit groups, nibbles, bytes, and 16-bit halves with masks (0xAAAAAAAA/0x55555555, etc.); in Python end with & 0xFFFFFFFF.

Problem

Given a 32-bit unsigned integer n, reverse the order of its bits and return the result as an unsigned integer. The bit at position i (counting from the least-significant end, 0..31) must end up at position 31 - i.

Examples

  • 43261596 (00000010100101000001111010011100) β†’ 964176192 (00111001011110000010100101000000) β€” the two 32-bit strings are mirror images.
  • 4294967293 (11111111111111111111111111111101) β†’ 3221225471 (10111111111111111111111111111111) β€” the single 0 moves from position 1 to position 30.
  • 1 (00...001) β†’ 2147483648 (10...000) β€” the lone set bit moves from position 0 to position 31.

Constraints

  • The input is a 32-bit unsigned integer.

Follow-up: if the function is called many times, can you avoid redoing full work each time (caching, or a fixed-step approach)?

Think about it first

Hint 1 Build the answer one bit at a time: pull the lowest bit off `n`, and push it onto a `result` that you keep shifting left. After 32 pushes the first bit you read sits at the top.
Hint 2 Each step is `result = (result << 1) | (n & 1)` followed by `n >>= 1`. Run it exactly 32 times so leading zeros are placed too.
Hint 3 For a constant-step version: reversing a bit string is the same as swapping its two halves, then swapping halves within each half, and so on. With masks you can swap all adjacent bits at once, then 2-bit groups, then nibbles, bytes, and 16-bit halves β€” five masked steps, no loop.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.