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.
result = 0
for _ in range(32):
result = result * 2 + (n & 1)
n >>= 1
return result- result
- 0
- rounds
- 1
Peel the lowest bit, 0, and push it: result = result × 2 + 0.
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.
Reversing all 32 bits of 1 gives which bit set?
- ABit 31
- BBit 0
- CNo bits
Show the answer
Bit 31. Bit 0 moves to the other end, bit 31.
Reverse the bits
Write n as 32 bits (with leading zeros), reverse their order, and return the resulting number.
n = 6 → 1610612736
0 ≤ n ≤ 2^31 − 1 · the answer can reach 2^32 − 1: return a long