176/670

176. Reverse Bits

Easy

You are given a 32-bit unsigned integer n. Reverse the order of its 32 bits — the bit that was in position 0 (the least significant) moves to position 31 (the most significant), and so on — and return the resulting unsigned integer.

Think of n as a fixed-width string of exactly 32 bits, including any leading zeros: you are mirroring that whole 32-character pattern end to end, not just the significant part.

Return the reversed value as a plain non-negative integer in the range 0 to 2^32 - 1.

Example 1:

Input: n = 43261596 # 00000010100101000001111010011100

Output: 964176192 # 00111001011110000010100101000000

Explanation: Written as 32 bits and mirrored end to end, the pattern of n becomes 964176192.

Example 2:

Input: n = 4294967293 # 11111111111111111111111111111101

Output: 3221225471 # 10111111111111111111111111111111

Explanation: Only bit 1 is a zero; reversing sends it to position 30, giving 3221225471.

Constraints:

  • 0 ≤ n ≤ 2³² - 1 (n fits in 32 unsigned bits)
  • The width is always exactly 32 bits, including leading zeros

Hints:

Build the answer bit by bit: shift the result left, take n's lowest bit, then shift n right. Repeat 32 times.

For a slicker version, swap bits in halves: exchange the two 16-bit halves, then 8-bit groups, then 4, 2, and 1 — a divide-and-conquer mask-and-shift that reverses all 32 bits in a handful of steps.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: n = 43261596

Expected output: 964176192