Reverse Bits
The drill: Read a 32-bit integer's bits back to front — the bit in position 0 swaps with the bit in position 31, position 1 with 30, and so on down the middle — and return the mirrored value.
A 32-bit unsigned integer arrives, and the task is to mirror its bit pattern — the bit sitting in position 0 moves to position 31, position 1 moves to position 30, and so on toward the middle.
The output is a fresh 32-bit unsigned value built entirely from that mirrored arrangement; nothing about the number's magnitude carries over, only the raw bit layout matters.
Because the input always occupies exactly 32 bits, leading zero bits in the original become trailing zero bits in the reversed result, and the reverse is true as well.
- the input is always exactly 32 bits wide, treated as unsigned
- the output is also a 32-bit unsigned value, never reported as negative
- every bit position matters, including leading and trailing zeros
- the mapping is a fixed one-to-one mirror, position i swaps with position 31 − i
HINT 1 THE NUDGE
Rendering the number as a padded binary string and reversing the string works, but it pays for building and re-parsing text just to move bits around.
HINT 2 THE STRUCTURE
Bit i of the input always lands at bit (31 − i) of the output — no bit needs to know about any other bit to find its new home.
HINT 3 ONE STEP FROM THE ANSWER
Walk all 32 positions: pull bit i out with (n >> i) & 1, then OR it into the result shifted to (31 − i). One pass, no text involved.
n=12 is 1100 in its low byte — bits 3 and 2 are set. Row 0 shows positions 7..0; row 1 will hold the mirrored positions 31..24. The unshown middle 24 bits stay zero throughout.
class Solution:
def reverseBits(self, n: int) -> int:
result = 0
for i in range(32):
bit = (n >> i) & 1
result |= bit << (31 - i)
return resultclass Solution:
def reverseBits(self, n: int) -> int:
bits = format(n, "032b")
return int(bits[::-1], 2)class Solution {
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
int bit = (n >>> i) & 1;
result |= bit << (31 - i);
}
return result;
}
}class Solution {
public int reverseBits(int n) {
StringBuilder bits = new StringBuilder();
for (int i = 31; i >= 0; i--) {
bits.append((n >>> i) & 1);
}
return (int) Long.parseLong(bits.reverse().toString(), 2);
}
}✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED