You are given a 32-bit unsigned integer n. Reverse the bits in its 32-bit binary representation and return the resulting unsigned integer.
Function Signature
def reverse_bits(n: int) -> int:
Rules
-
Read
n
as exactly 32 bits, including leading zeros. Bit
i
of the input (bit 0 is the least significant) becomes bit
31 - i
of the output.
-
Return the result as an unsigned value from 0 to 4294967295. A result with bit 31 set is a large positive number, never a negative one.
Constraints
-
0 <= n <= 2^32 - 1
(that is,
n <= 4294967295
)
Examples
Input: n = 60
Output: 1006632960
As 32 bits, 60 is 00000000000000000000000000111100. Reversed, it is 00111100000000000000000000000000, which has bits 26 through 29 set: 0x3C000000, or 1006632960.
Input: n = 1
Output: 2147483648
The only set bit moves from position 0 to position 31, so the result is the value of bit 31 alone, 2147483648.
Input: n = 4294967293
Output: 3221225471
4294967293 is 11111111111111111111111111111101, all ones except bit 1. After the reversal the single zero sits at bit 30, giving 10111111111111111111111111111111, which is 0xBFFFFFFF, or 3221225471.