Reverse 32 Bits
You get a non-negative integer n. Write it as a 32-bit unsigned number, with leading zeros so that it has exactly 32 bits.
Reverse the order of those 32 bits: bit 0 (the lowest) moves to bit 31, bit 1 moves to bit 30, and so on.
Return the new 32-bit number as an unsigned integer. The result is never negative.
Note for JavaScript
Bitwise operators in JavaScript work on 32-bit signed integers, so x << 1 can give a negative number when bit 31 is set. Finish with result >>> 0 to get the unsigned value, or build the result with result * 2 + bit.
Hint
Repeat 32 times: take the lowest bit of n, add it to the low end of the result after shifting the result one place to the left, then shift n one place to the right.
Examples
Example 1
- Input:
- 1
- Output:
- 2147483648
Only bit 0 is set. After the reverse, only bit 31 is set, and 2^31 = 2147483648.
Example 2
- Input:
- 6
- Output:
- 1610612736
6 is 110 in binary, so bits 1 and 2 are set. They move to bits 30 and 29: 2^30 + 2^29 = 1610612736.
Example 3
- Input:
- 4294967294
- Output:
- 2147483647
All bits are 1 except bit 0. After the reverse, all bits are 1 except bit 31, which is 2^31 - 1 = 2147483647.
Constraints
0 <= n <= 2^32 - 1(that is,4294967295)- The answer is also between
0and2^32 - 1.
Run checks your code against the 3 examples. Submit checks it against all 203 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.