Reverse Bits solution explained
The Reverse Bits solution takes the lowest bit of the input 32 times and pushes each one onto the right end of a result that shifts left every round, so the first bit read ends up in the highest position. It runs a fixed 32 iterations with O(1) memory; the care is in keeping all 32 positions, including leading zeros, and keeping the result unsigned.
By Evin JohnPublished 7 min read
The problem in plain words
You get an unsigned 32-bit integer. Write all 32 of its bits, leading zeros included, then read them from right to left. Return the number that this reversed pattern represents. The phrase "all 32" is the whole trick: the number 1 is not just a single bit; it is 31 zeros followed by a 1, so its reversal is a 1 followed by 31 zeros.
| Input | 32-bit pattern (shortened) | Reversed value |
|---|---|---|
| 1 | 000...0001 | 2147483648 (only the top bit set) |
| 6 | 000...0110 | 1610612736 (binary 0110 followed by 28 zeros) |
| 240 (0xF0) | 000...11110000 | 251658240 (0x0F000000) |
| 2147483648 | 1000...000 | 1 |
| 0 or 4294967295 | all zeros or all ones | the same value |
Where it shows up
Bit reversal is a real operation in signal processing (the fast Fourier transform reorders data by bit-reversed index), in some checksum and hashing code, and in hardware work. In interviews it is a compact check of shift and mask fluency and of whether you think about fixed widths and signed types. Embedded and systems interviewers in particular tend to ask how you would make it faster.
Follow-up questions
- Called many times. Precompute the reversal of every 8-bit value, then reverse the four bytes of the input and look each one up. Four lookups and some shifts per call.
- No loop at all. Swap the two 16-bit halves, then bytes inside each half, then 4-bit groups, pairs and single bits, each with one mask. Five steps for 32 bits; shown below.
- A different width. For 64 bits the loop runs 64 times and the mask version gains one more swap.
- Reverse only the significant bits. A different question: 6 (110) would become 3 (011). Clarify which one is meant.
- Is the pattern a palindrome? Compare the value with its reversal.
A clear first answer: go through a string
Format the value as binary padded to exactly 32 characters, reverse the string, and parse it in base 2. The padding is what makes it correct; without it, small numbers lose their leading zeros and the answer is wrong. It allocates a string and is slower than needed, which gives you something to improve.
def reverse_bits_text(n):
bits = format(n & 0xFFFFFFFF, "032b") # exactly 32 characters, leading zeros kept
return int(bits[::-1], 2)The expected answer: move one bit at a time
Keep a result that starts at zero. Thirty-two times: shift the result left by one to make room, copy the input's lowest bit into the result's lowest position with an OR, then shift the input right by one. The first bit you take from the input is pushed left 31 more times, so it ends up in the top position, which is exactly where the mirror image needs it. Because the loop always runs 32 times, leading zeros of the input correctly become trailing zeros of the result.
def reverse_bits(n):
n &= 0xFFFFFFFF
result = 0
for _ in range(32):
result = (result << 1) | (n & 1) # move the lowest bit of n onto result
n >>= 1
return resultfunction reverseBits(n) {
let result = 0;
for (let i = 0; i < 32; i++) {
result = ((result << 1) | (n & 1)) >>> 0; // keep result unsigned
n >>>= 1;
}
return result;
}In JavaScript, result << 1 produces a signed 32-bit value, so after the top bit is set the result would print as negative. Applying >>> 0 each round keeps it in the unsigned range, and shifting the input with >>> instead of >> stops the sign bit from being copied into it.
The mask-swap version for a follow-up
Reversing 32 bits is the same as swapping the two halves, then reversing each half. Apply that idea all the way down and you get five lines: swap 16-bit halves, swap bytes within halves, swap 4-bit groups within bytes, swap pairs, swap neighbors. Each line moves every bit at once using a mask that selects one side of each pair.
def reverse_bits_by_swaps(n):
n &= 0xFFFFFFFF
n = ((n >> 16) | (n << 16)) & 0xFFFFFFFF # swap the two halves
n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8) # swap bytes in each half
n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4) # swap nibbles
n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2) # swap bit pairs
n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1) # swap single bits
return nCost of each approach
| Approach | Time | Extra memory | Notes |
|---|---|---|---|
| Pad, reverse and parse a string | O(32) plus allocation | A 32-character string | Clear; slow if called often |
| Bit-by-bit loop | 32 iterations, O(1) | O(1) | The expected answer |
| Byte lookup table | 4 lookups per call | 256 precomputed values | Best for many calls |
| Mask swaps | 5 steps | O(1) | Branch-free; easy to get a mask wrong |
Inputs to test
- 1, which must become 2^31. Code that drops leading zeros returns 1 instead.
- 2^31, which must become 1. Signed-type bugs often show up here.
- 0 and 2^32 - 1, which are their own reversals.
- A random value reversed twice, which must give back the original.
- An asymmetric value such as 0xF0, where a swap in the wrong direction is easy to spot.
Common slips
- Looping only while the input is non-zero, which skips the trailing shifts and leaves the result too small.
- Formatting the binary string without padding to 32 characters.
- Using
>>on a value with the top bit set in JavaScript, Java or C with signed types, so ones flood in from the left. - Returning a negative number in JavaScript because the final
>>> 0was left out. - Shifting the result after the last OR as well, which pushes everything one place too far.
How to explain it out loud
Fictional example
- Candidate
- I'll treat the input as exactly 32 bits, so leading zeros count. The simplest mental model is a conveyor: I take bits off the right end of the input and push them onto the right end of the result.
- Candidate
- Each round the result shifts left first, so the first bit I took keeps moving up. After 32 rounds it sits in the top position. For input 1, the single 1 bit is taken first and ends up as 2 to the 31.
- Candidate
- That is a fixed 32 steps and constant memory. If this runs in a hot loop, I'd switch to a 256-entry table of reversed bytes.
Related problems
Number of 1 Bits uses the same unsigned-shift care to count instead of rebuild. Reverse Integer reverses decimal digits instead of binary ones, where the hard part becomes overflow rather than width. Sum of Two Integers is the next step if you want more practice with masks and signed values.
Practice support from Natively
For a problem where one missing >>> 0 changes the answer, a second pair of eyes helps. During practice, Natively can read the prompt and your code from a screenshot on Mac or Windows, explain the conveyor idea if it has not clicked, and suggest the edge inputs worth tracing. Its transcript of a mock round lets you check whether you stated the 32-bit assumption before you started coding.
Questions people ask
How do you reverse the bits of a 32-bit integer?
Start a result at zero and repeat 32 times: shift the result left, OR in the input's lowest bit, and shift the input right. The first bit taken ends in the highest position.
Why does reversing 1 give 2147483648?
As a 32-bit value, 1 is 31 zeros followed by a 1. Its mirror image is a 1 followed by 31 zeros, which is 2^31, or 2147483648 as an unsigned number.
Why does my JavaScript Reverse Bits return a negative number?
Bitwise operators in JavaScript return signed 32-bit values. Apply >>> 0 to the result, and shift the input with >>> rather than >>, to keep everything unsigned.
How can you make Reverse Bits faster if it is called many times?
Precompute the reversal of every byte in a 256-entry table and combine four lookups, or use five mask-and-swap steps that reverse halves, bytes, nibbles, pairs and single bits.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
