Reverse Bits

EasyBit Manipulation🧩 Bit ManipulationLeetCode #190 ↗Updated

Problem

You get a number n viewed as a pattern of exactly 32 bits. Return the number whose bit pattern is that sequence read backwards: bit 0 swaps with bit 31, bit 1 with bit 30, and so on. Leading zeros count, so a small input can become a huge output. (Java has no unsigned int, so the bits are simply carried in an int.)
Inputn = 43261596 (00000010100101000001111010011100)Output964176192 (00111001011110000010100101000000)
Inputn = 2147483644 (0111...11100)Output1073741822 (00111...1110)
Inputn = 1Output-2147483648 (only bit 31 set)

Input is any 32-bit pattern  ·  Follow-up: if the function is called many times, how would you make it faster?

Try it yourself

Java
class Solution {
    public int reverseBits(int n) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Reversing 32 bits is the same as swapping the two 16-bit halves, then the bytes inside each half, then the nibbles, pairs and single bits — 5 masked swaps instead of 32 single-bit moves.
PatternBit Manipulation

Instinct Pairs that cancel, counting 1s, powers of two, subsets as numbers, or 'no + or - allowed' - drop to binary and use XOR, AND, OR and shifts.

Memory hack XOR is a forgetful twin detector - see something twice and it vanishes; n & (n-1) snips off the last lit bulb.

Open the Bit Manipulation guide →

Approaches

Brute ForceBinary String, Reverse, Parse

Time O(32)Space O(32)

Write n as a binary string, left-pad it to 32 characters so leading zeros are not lost, reverse the string and parse it back. Parsing goes through a long because a pattern starting with 1 overflows Integer.parseInt.

Java
public int reverseBits(int n) {
    String bits = String.format("%32s", Integer.toBinaryString(n)).replace(' ', '0');
    String reversed = new StringBuilder(bits).reverse().toString();
    return (int) Long.parseLong(reversed, 2); // long: top bit may be 1
}

Correct and readable, but allocates strings and ignores how bits actually work.

At a glance

LevelApproachTimeSpace
Brute ForceBinary String, Reverse, ParseO(32)O(32)
BetterShift Bits One at a TimeO(32)O(1)
OptimalDivide & Conquer Mask SwapsO(1) — 5 stepsO(1)
Common pitfalls
  • Using >> instead of >>> — negative inputs keep refilling with 1s.
  • Stopping when n == 0 — the remaining zero bits still have to shift result left.
  • Forgetting to pad the binary string to 32 chars, which drops leading zeros.
Interview tips
  • Clarify that the input is a 32-bit pattern and that Java returns it in a signed int.
  • Write the shift loop first, then raise the follow-up and show the mask swaps or a byte table.
  • Check 1 → Integer.MIN_VALUE and -1 → -1 out loud.
Pattern
Bit-by-bit shifting / masked swaps → reorder, count or mirror the bits of a fixed-width integer.
My notes saved in this browser