DSA Factory
Free Math and bits lessonsMath and bits · Stage 3 · Bit tricks · Step 4

Mirror the bits

Reverse the 32 bits of a number. About 9 minutes.

Reverse a number, in base 2

You already reversed 123 into 321 by peeling digits off the end and pushing them onto a new number. Do the very same with bits: peel the last bit, then push it on by doubling the result and adding the bit.

Always do exactly 32 rounds, so leading zeros of the input become trailing zeros of the answer, as they should for a 32-bit number.

32 rounds: always, so leading zeros become trailing zeros.
In code
result = 0
for _ in range(32):
    result = result * 2 + (n & 1)
    n >>= 1
return result
n = 6: its lowest bits are 110
1
0
1
1
0
2
n & 1
result
0
rounds
1

Peel the lowest bit, 0, and push it: result = result × 2 + 0.

Move 1 of 4

Big answers

Reversing can drop a 1 into bit 31, the very top. The answer can then be as large as 2 to the power 32, minus 1, which is more than a signed 32-bit int can hold.

In Java or C++, return it in a 64-bit type or treat it as unsigned. The number 1 reverses to 2,147,483,648.

1: reverses to 2,147,483,648 (bit 31).
Quick check

Reversing all 32 bits of 1 gives which bit set?

  1. ABit 31
  2. BBit 0
  3. CNo bits
Show the answer

Bit 31. Bit 0 moves to the other end, bit 31.

Your problem

Reverse the bits

Write n as 32 bits (with leading zeros), reverse their order, and return the resulting number.

Example
n = 6 → 1610612736

0 ≤ n ≤ 2^31 − 1 · the answer can reach 2^32 − 1: return a long

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve