Bit Manipulation Counting and shifting bits
118. Reverse Bits
You are given a whole number n between 0 and 232 − 1. Write n in binary with exactly 32 digits,
adding zeros on the left when it needs fewer. Reverse the order of those 32 digits and return the number they
now spell.
The digits keep their values. Only their order changes: the rightmost digit of n becomes the leftmost digit
of the answer, and the leftmost digit of n becomes the rightmost.
The answer is also between 0 and 232 − 1, and it is never negative. In C++, Java, Go, Rust and C#,
n and the answer are 64-bit integers, because a signed 32-bit int cannot hold the numbers from
231 up. In Python and JavaScript they are ordinary numbers.
Example 1
Input: n = 11
3489660928Explanation: In 32 digits, 11 is 0000 0000 0000 0000 0000 0000 0000 1011 (spaces added for reading). Reversed, it is
1101 0000 0000 0000 0000 0000 0000 0000, which is 231 + 230 + 228 =
3489660928.
Example 2
Input: n = 2147483648
1Explanation: 2147483648 is 231, a single 1 in the leftmost of the 32 digits. Reversed, that 1 is the rightmost digit, so the answer is 1.
Example 3
Input: n = 4294967295
4294967295Explanation: All 32 digits are 1, so their order makes no difference. This is the largest n, and its answer is the
largest possible answer.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ n ≤ 232 − 1
Clarifying questions
What you would ask an interviewer before writing any code.