257. Bits in Reverse
A legacy sensor sends 32-bit status words with the least significant bit first, while the new controller reads them with the most significant bit first. The adapter has to mirror the word: bit 0 becomes bit 31, bit 1 becomes bit 30, and so on, always across exactly 32 positions even when the word has leading zeros.
The unsigned 32-bit word is passed as the non-negative integer n (so it can be as large as 4294967295). Return the unsigned value obtained by reversing the order of its 32 bits. For example n = 12 is 00000000000000000000000000001100 and its mirror is 00110000000000000000000000000000, which is 805306368. Run a fixed number of steps and use constant extra space.
Example 1
- Input:
- n = 12
- Output:
- 805306368
- Explanation:
12 has bits 1100 at positions 3 and 2, which mirror to positions 28 and 29, giving 805306368.
Example 2
- Input:
- n = 4026531840
- Output:
- 15
- Explanation:
4026531840 is 0xF0000000, whose four high bits mirror to the four low bits, giving 15.
Example 3
- Input:
- n = 4294967295
- Output:
- 4294967295
- Explanation:
All 32 bits are set, so the reversal is the same value.
Constraints
0 ≤ n ≤ 232 - 1
The result also lies in [0, 232 - 1], so it never needs a sign.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(1)
- Space
- O(1)