InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Reverse Bits

easy Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug