Reverse Bits
Easy · bit manipulation
Write a non-negative integer n as a row of exactly 32 bits, adding 0 digits on the left if the number is short. Reverse the order of the 32 bits, so the first bit becomes the last and the last becomes the first, then return the non-negative integer that the reversed row represents.
For example, with 8 bits instead of 32, 00000110 reversed is 01100000. Here the row is 32 bits long, so the zeros that were on the left end up on the right.
Examples
Example 1
Input: n = 6
Output: 1610612736
6 is 110, which is 29 zeros followed by 110. Reversed, it is 011 followed by 29 zeros, and that row of bits is 1610612736.
Example 2
Input: n = 1
Output: 2147483648
Only the last bit is 1. After the reversal only the first bit is 1, which is 2^31.
Example 3
Input: n = 4294967295
Output: 4294967295
All 32 bits are 1, so reversing changes nothing.
Constraints
- 0 <= n <= 2^32 - 1 (n fits in 32 bits)