150NeetCode 150

147.Reverse Bits

EasyBlind 75Bit Manipulation ยท 4/7

Problem

Reverse the bits of a given 32-bit integer n: bit 0 swaps with bit 31, bit 1 with bit 30, and so on. Return the resulting integer.

All 32 positions take part, including leading zeros โ€” so a small number turns into a large one. In Java there is no unsigned int, so a result whose top bit is 1 is simply returned as a negative int with the correct bit pattern.

Examples

Input:  n = 43261596
Output: 964176192
Explanation:
43261596  = 00000010100101000001111010011100
reversed  = 00111001011110000010100101000000 = 964176192
Input:  n = 2147483644
Output: 1073741822
Explanation:
2147483644 = 01111111111111111111111111111100
reversed   = 00111111111111111111111111111110 = 1073741822

Constraints

  • 0 <= n <= 2^31 - 2
  • n is even.
  • The input must be treated as a 32-bit value (leading zeros count).

Follow-up: if this function is called many times, how would you optimize it?

๐Ÿ’ก Key Insight

Reversing is just moving bit i to position 31 - i. The simplest correct way is to pop bits off the right of n and push them onto the right of the result, 32 times. A faster fixed-cost way is divide and conquer: swap the two 16-bit halves, then the 8-bit halves inside each half, then 4-, 2- and 1-bit groups โ€” five mask-and-shift steps reverse all 32 bits.

Brute Force (String Reversal)

TimeO(32) = O(1), but with string allocation and parsing overhead.SpaceO(32) = O(1) for the strings.

Intuition

Turn the number into its 32-character binary string (padding with leading zeros), reverse the string, and parse it back as an unsigned base-2 number.

Algorithm

  1. s = Integer.toBinaryString(n), left-padded with '0' to length 32.
  2. Reverse s.
  3. Return Integer.parseUnsignedInt(reversed, 2) (handles results with the top bit set).

Visualization

n = 43261596
padded  : 00000010100101000001111010011100
reversed: 00111001011110000010100101000000 โ†’ 964176192

Code

java
class Solution {
    public int reverseBits(int n) {
        String bits = Integer.toBinaryString(n);
        // pad with leading zeros so all 32 positions are reversed
        String padded = "0".repeat(32 - bits.length()) + bits;
        String reversed = new StringBuilder(padded).reverse().toString();
        // parseUnsignedInt accepts values up to 2^32 - 1 (top bit set โ†’ negative int)
        return Integer.parseUnsignedInt(reversed, 2);
    }
}

Complexity

  • Time: O(32) = O(1), but with string allocation and parsing overhead.
  • Space: O(32) = O(1) for the strings.

Complexity Comparison

Approach Time Space
String Reversal O(32) + string overhead O(32)
Bit by Bit O(32) O(1)
Divide and Conquer Masks O(5) O(1)

Common Pitfalls

  • Stopping the loop when n == 0 โ€” leading zeros must still be shifted into result, so always run all 32 iterations.
  • Using >> instead of >>> in the mask approach โ€” an arithmetic shift copies the sign bit into the vacated positions and corrupts the result for negative intermediates.
  • Using Integer.parseInt(s, 2) on a 32-bit string that starts with 1 โ€” it throws NumberFormatException; use parseUnsignedInt.
  • Forgetting to pad Integer.toBinaryString to 32 characters โ€” it drops leading zeros, so you would reverse too few bits.
  • Panicking at a negative output in Java โ€” the bit pattern is what matters; a set top bit simply prints as a negative int.