bit-manipulation
Reverse all 32 bits of a given 32-bit integer n and return the resulting integer.
Treat n as a fixed-width 32-bit binary number (with leading zeros up to 32 bits), so bit 0 moves to bit 31, bit 1 moves to bit 30, and so on.
Input / output
- Input:
n: int(32-bit integer; test fixtures use even values in[0, 2^31 - 2]so both input and reversed output fit in signed 32-bitint) - Output:
int— the 32-bit bit-reversed integer
Constraints
nis a 32-bit integer (0 <= n <= 2^31 - 2, even in all fixtures)- Output fits in a non-negative 32-bit signed integer (
0 <= output <= 2^31 - 1)
Follow-up
If this function is called many times, how can you reverse 32 bits in O(log 32) = 5 divide-and-conquer bit-swap masks (16-bit, 8-bit, 4-bit, 2-bit, 1-bit) or with a 256-entry byte lookup table?
Examples
Example 1
Input: n = 43261596
Output: 964176192
Example 2: zero
Input: n = 0
Output: 0
Example 3: single bit at index 1
Input: n = 2
Output: 1073741824