Write the integer n as exactly 32 binary digits, padding with 0s on the left as needed. Reverse the order of those 32 digits, so the rightmost digit becomes the leftmost, and return the number the reversed digits spell out.
The padding counts: the zeros at the front of n end up at the back of the answer, which is why a small n usually gives a large result.
Example 1
Input: n = 40
Output: 335544320
40 = 00000000000000000000000000101000
335544320 = 00010100000000000000000000000000
Read the second line right to left and you get the first.
Example 2
Input: n = 1073741824
Output: 2
1073741824 is 2³⁰: its only 1 sits second from the left among the 32 digits. Reversed, it sits second from the right, which is 2.
Example 3
Input: n = 2147483646
Output: 2147483646
The 32 digits are 0, thirty 1s, then 0. That reads the same in both directions, so the answer is n itself.
Constraints
0 <= n <= 2³¹ - 2n is even.Together these keep both the input and the answer inside a signed 32-bit integer: the highest of the 32 digits is always 0, and because the lowest one is too, so is the highest digit of the answer. You never need an unsigned type.
Move the bits one at a time: take the lowest bit of n and add it at the low end of the answer, after shifting the answer left to make room. The first bit you take ends up highest.
The input is always 32 binary digits, so the work is fixed: 32 digits to move, whatever n is. Every approach here is fast. What separates them is how directly they talk to the bits.
Time O(1)Space O(1)
The full walkthrough and code are part of Premium
40
335544320