You are given a number n that fits in 32 bits. Write it as exactly 32 binary digits, leading zeros included, and reverse that string of digits.
Return the number the reversed digits stand for. Bit 0 of n becomes bit 31 of the answer, bit 1 becomes bit 30, and so on.
Example 1
Input: n = 305419896 Output: 510274632 Why: 0x12345678 read backwards bit by bit is 0x1E6A2C48
2 more examples and the constraints
Example 2
Input: n = 6 Output: 1610612736 Why: binary 110 at the bottom becomes 011 at the top
Example 3
Input: n = 2147483646 Output: 2147483646 Why: 0111…1110 is the same backwards
Constraints
- 0 ≤ n ≤ 2,147,483,646 (2³¹ − 2)
- n is even, so bit 0 is 0 and the answer always fits in a signed 32-bit integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Bit by bitO(32)
- Swap with masksO(1)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work per call | Verdict |
|---|---|---|---|
| Bit by bit | O(32) | Passes; easiest to explain | |
| Swap with masks | O(1) | Best; 5 steps instead of 32 |
Both are constant time for 32-bit numbers. Work counts the basic steps per call: 32 against 5.
Edge cases to test
- Zero. 0 reversed is still 0.
- Leading zeros matter. 6 is 110, but as 32 bits it has 29 zeros in front. They end up at the bottom.
- Top bit of the answer. n is even, so bit 31 of the answer is 0 and it fits a signed int.
- Symmetric patterns. 2147483646 (0111…1110) comes back unchanged.
Common mistakes
- Looping only while n > 0, which skips the leading zeros and puts bits in the wrong place.
- Using the signed shift
>>in Java or TypeScript on a value with the top bit set, which drags in 1s. - Reversing the decimal digits or a binary string without padding it to 32 characters.
How to talk through it
- 1Clarify. Exactly 32 bits, leading zeros included? Signed or unsigned result?
- 2Give the loop. Pop the lowest bit of n and push it onto the result, 32 times.
- 3Answer the follow-up. For many calls, swap blocks with masks in 5 steps, or cache reversed bytes in a 256-entry table.
- 4Code the masks. Name each mask as you write it: halves, bytes, nibbles, pairs, bits.
- 5Test out loud. Run n = 6 and n = 0, and check where bit 1 lands.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?