n and res bit i of n is read (right band) and written into bit 31 − i of res (left band) · dim = not written yet
public int reverseBits(int n) { int res = 0; for (int i = 0; i < 32; i++) { int bit = (n >>> i) & 1; // read bit i res = res | (bit << (31 - i)); // write it at the mirror spot } return res;}
- i
- —
- bit
- —
- 31 − i
- —
- res
- 0
Why it works
- Brute force through strings: format n as a 32-character binary string (zero-padded!), reverse it and parse it back. Also O(32), but it allocates strings and hides the bit operations interviewers want to see.
- Read bit i, write bit 31 − i.
(n >>> i) & 1brings bit i down to position 0 and masks everything else away;bit << (31 − i)lifts it to its mirror position, and OR drops it intoreswithout touching the bits already written. - Always 32 rounds: leading zeros of n become trailing zeros of the answer, so the loop cannot stop early when n runs out of 1s. O(32) = O(1) time, O(1) space.
- Pitfall: signed shifts. Java has no unsigned
int.>>copies the sign bit, so use>>>to read the bits of annwith bit 31 set. The returnedintis negative when bit 31 of the answer is set; the page shows the same 32 bits as an unsigned number (Integer.toUnsignedString(res)). - Follow-up, called many times: cache the reversal of each byte (a 256-entry table) and assemble four of them, or swap halves, then quarters, then pairs with masks: 5 steps instead of 32.