15% off all plans & roadmaps Use code

See plans

Reverse Bits

Updated

TL;DR: Reverse the order of all 32 bits of an integer, including leading zeros, and return the result as a signed 32-bit value. The fastest method swaps halves of the word with masks in 5 steps. The common 32-step shift loop is also fine.

Problem

You are given a signed 32-bit integer n. Treat it as a fixed-width 32-bit two's-complement pattern. Bit 31 is the sign bit, bits 30 through 0 hold the rest of the value, and leading zero bits count as part of the pattern.

Reverse the order of all 32 bits. The bit at position 0 moves to position 31, the bit at position 1 moves to position 30, and so on. Read the new 32-bit pattern as a signed two's-complement integer and return it.

Implement Solution.reverseBits(n). Both the input and the returned value are signed 32-bit integers.

Example 1

Input: n = 1
Output: -2147483648
Explanation: The pattern for 1 has only its lowest bit set. After reversal that bit sits at position 31, which stands for -2^31 in a signed 32-bit integer.

Example 2

Input: n = 5
Output: -1610612736
Explanation: The set bits of 5 are at positions 0 and 2. They move to positions 31 and 29, which gives the signed value -1610612736.

Example 3

Input: n = -2
Output: 2147483647
Explanation: The pattern for -2 is all ones except the lowest bit. Reversed, bit 31 is clear and every lower bit is set, which equals 2147483647.

Constraints

  • -2^31 <= n <= 2^31 - 1
  • n is an integer
  • n is represented with exactly 32 bits, including leading zero bits
  • The returned value is read as a signed 32-bit two's-complement integer
  • -2^31 <= returned value <= 2^31 - 1

Constraints that matter

  • The width is fixed at 32 bits, so every approach does a constant amount of work. Even a 32-iteration loop counts as O(1), and speed differences come down to constant factors.
  • Leading zeros are part of the pattern. Any method that stops when the number reaches zero, or that uses a variable-length binary string, produces wrong positions.
  • Input and output are signed. Negative inputs must be read by their two's-complement pattern, and a result with bit 31 set must come back negative.
  • The value range is exactly 32 bits, so Java, C# and C++ need unsigned or logical shifts, and Python and JavaScript need explicit masking or conversion.

View on LeetCode

Hints

Hint 1

This is a bit manipulation problem with a fixed word size.

Hint 2

Write the 32-bit pattern of n as a string of exactly 32 characters, reverse the string, and parse it back as a base-2 number.

Solution

Intuition

This is a bit manipulation problem with a fixed word size. The statement says the input has exactly 32 bits, leading zeros included. That tells you to think in positions 0 through 31, never in terms of the number's value or its binary string length.

Picture a shelf of 32 boxes flipped end to end by cutting it in halves, swapping the halves, and repeating inside each half. Each mask pair does one such cut-and-swap pass across the whole word, so five passes replace 32 single moves.

Two moves cover everything you need. n & 1 reads the lowest bit, and shifting moves bits sideways. Read bits from the low end of the input and push each one onto the low end of a new number after shifting it left. The first bit read ends up at the top, and after 32 rounds the order is reversed.

There is a second view. A bit at position p must land at position 31 - p. Since 31 is 11111 in binary, 31 - p is the same as flipping all five bits of the position number p. Swapping the two 16-bit halves flips the top bit of every position number. Swapping adjacent bytes inside each half flips the next one, and so on down to swapping adjacent single bits. Five masked swaps give the same answer as 32 loop rounds.

The last detail is the sign. Languages with fixed 32-bit integers (Java, C#, C++, Go with int32) give you the signed reading for free once the bit pattern is right. Python integers have no fixed width. There you mask the input to 32 bits and subtract 2^32 at the end if bit 31 is set.

Watch the pattern animation

Worked example

Input: n = -2147483648
Output: 1
Explanation: The input -2147483648 has only bit 31 set, so its pattern is 1 followed by 31 zeros. Reversing the order moves that single set bit to position 0. The result is 0...01, which is 1. The input and output are mirror images of Example 1.

Approach 1: Binary string, reverse, parse

Write the 32-bit pattern of n as a string of exactly 32 characters, reverse the string, and parse it back as a base-2 number. This is how most people first solve it, because the problem reads like a string reversal.

The only real work is getting a faithful 32-character string. Plain binary conversion drops leading zeros and may print a minus sign for negatives. You must pad to 32 characters and take the bits of the unsigned pattern. The parsed value must then be read as signed.

Steps

  1. Take the low 32 bits of n as an unsigned pattern.
  2. Build a string of 32 characters, one per bit, from bit 31 down to bit 0.
  3. Reverse the string.
  4. Parse the reversed string as a base-2 number.
  5. If the parsed value is 2^31 or more, subtract 2^32 (or use an unsigned-to-signed conversion).
  6. Return the signed value.

Dry run

Input n = -2147483648. Its unsigned pattern is 0x80000000.

  • The 32-character string is 1 followed by 31 zeros.
  • Reversed, it is 31 zeros followed by 1.
  • Parsed in base 2, that is the value 1.
  • 1 is below 2^31, so no sign adjustment is needed. The answer is 1.

Complexity

TimeO(1)
SpaceO(1)

The string always has exactly 32 characters, so building it, reversing it, and parsing it each take a fixed 32 steps. The string uses 32 characters of memory no matter what n is. The constants are larger than for pure bit work because of allocation and parsing.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverseBits(self, n: int) -> int:
        # 32-character pattern of the unsigned value, leading zeros kept
        bits = format(n & 0xFFFFFFFF, '032b')
        value = int(bits[::-1], 2)
        # read the pattern as signed
        if value >= 1 << 31:
            value -= 1 << 32
        return value

Approach 2: Shift loop, 32 rounds

What's slow: the string version allocates text, reverses it, and parses it, only to move 32 bits around. It also hides the sign and padding traps inside library calls.

The insight that fixes it: work on the bits directly. Read the lowest bit of the input with n & 1, shift the result left, and push the bit onto its low end. Then shift the input right.

Repeat exactly 32 times so leading zeros are processed too. The first bit read is bit 0. By the end it has been shifted left 31 times, which puts it at position 31.

Steps

  1. Convert n to an unsigned 32-bit value so right shifts bring in zeros.
  2. Set result = 0.
  3. Repeat 32 times: set result = (result << 1) | (n & 1).
  4. After each round, shift n right by one.
  5. After the loop, if bit 31 of result is set, read it as signed (subtract 2^32 in Python).
  6. Return result.

Dry run

Input n = -2147483648, unsigned pattern 0x80000000, so only bit 31 is set.

  • Rounds 1 to 31 read bits 0 through 30. Every one is 0, so result stays 0 after each shift and OR.
  • Round 32 reads bit 31, which is 1. result = (0 << 1) | 1 = 1.
  • The loop ends. Bit 31 of result is clear, so the answer is 1.

Complexity

TimeO(1)
SpaceO(1)

The loop runs exactly 32 times, and each round does a fixed number of shifts, ANDs, and ORs. That is 32 constant-time rounds, so the time is O(1) with a constant of about 32 rounds. Only the input and the result are stored, so space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverseBits(self, n: int) -> int:
        n &= 0xFFFFFFFF  # keep only the 32-bit pattern
        result = 0
        for _ in range(32):
            result = (result << 1) | (n & 1)
            n >>= 1
        # read the pattern as signed
        if result >= 1 << 31:
            result -= 1 << 32
        return result
Bitwise AND - Counting Set Bits (Hamming Weight) pattern infographic for Reverse Bits

Solution pattern

Bitwise AND - Counting Set Bits (Hamming Weight)

Part of Bit Manipulation Patterns

Approach 3: Mask and swap in 5 stepsOptimalBitwise AND - Counting Set Bits (Hamming Weight)

What's slow: the loop touches one bit per round, so it needs 32 rounds. Each round does work that could be done for many bits at once.

The insight that fixes it: reversal is a divide and conquer. Reversing 32 bits equals swapping the two 16-bit halves, then reversing each half. Reversing a half equals swapping its two bytes and reversing each byte, and so on.

Each level swaps neighbouring blocks of one size across the whole word with one mask pair. The block sizes are 16, 8, 4, 2, 1, so five steps finish the job.

Steps

  1. Convert n to an unsigned 32-bit value.
  2. Swap the 16-bit halves: n = (n >> 16) | (n << 16).
  3. Swap adjacent bytes: n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8).
  4. Swap adjacent nibbles with masks 0xF0F0F0F0 and 0x0F0F0F0F, shifting by 4.
  5. Swap adjacent bit pairs with masks 0xCCCCCCCC and 0x33333333, shifting by 2.
  6. Swap adjacent bits with masks 0xAAAAAAAA and 0x55555555, shifting by 1.
  7. Read the result as signed and return it.

Dry run

Input n = -2147483648, unsigned pattern 0x80000000. Track the single set bit.

StepOperationValue (hex)Set bit position
0start0x8000000031
1swap 16-bit halves0x0000800015
2swap bytes: (0x8000 & 0xFF00) >> 8 = 0x800x000000807
3swap nibbles: (0x80 & 0xF0) >> 4 = 0x080x000000083
4swap pairs: (0x08 & 0xC) >> 2 = 0x020x000000021
5swap bits: (0x02 & 0xA) >> 1 = 0x010x000000010
6read as signed1bit 31 clear, so 1

The set bit moved from position 31 to position 0, and the answer is 1. In each step the other mask term, such as (n & 0x00FF00FF) << 8, was 0 because nothing sat in those positions.

Complexity

TimeO(1)
SpaceO(1)

There are exactly five swap steps, and each is a fixed number of shifts, ANDs, and ORs on one word. The work does not depend on the value of n. Only one word of state is kept, so space is O(1). This is about 6 times fewer rounds than the 32-iteration loop.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverseBits(self, n: int) -> int:
        n &= 0xFFFFFFFF
        n = ((n >> 16) | (n << 16)) & 0xFFFFFFFF
        n = (((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8)) & 0xFFFFFFFF
        n = (((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4)) & 0xFFFFFFFF
        n = (((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2)) & 0xFFFFFFFF
        n = (((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1)) & 0xFFFFFFFF
        # read the pattern as signed
        if n >= 1 << 31:
            n -= 1 << 32
        return n

Common mistakes

  • Using bin(n) or Integer.toBinaryString(n) without padding. Leading zeros vanish, so every position shifts. Pad to 32 characters, for example format(n & 0xFFFFFFFF, '032b') in Python.
  • Looping while n: instead of for _ in range(32). An input like 1 has 31 leading zeros that must be pushed through the result. Always run exactly 32 rounds.
  • Using n >>= 1 on a negative Java or JavaScript value. The arithmetic shift copies the sign bit, so the loop reads ones forever from the top. Use n >>>= 1, or an unsigned type in C++, Go and C#.
  • Skipping n &= 0xFFFFFFFF in Python. A negative Python integer has infinite sign extension, so n >> 1 never reaches 0 and the bits you read are wrong. Mask first.
  • Returning the unsigned result in Python or JavaScript. For Example 1 you would return 2147483648 instead of -2147483648. Subtract 2^32 in Python when bit 31 is set, and use | 0 in JavaScript.
  • Writing result = (result << 1) | n & 1 and trusting precedence. In most C-like languages & binds tighter than |, so it works, but it hides intent. Put parentheses around (n & 1) so the bit read is obvious.

Edge cases

  • n = 0 returns 0, since every bit is zero in both directions.
  • n = -1 (all 32 bits set) returns -1, because reversing a pattern of all ones changes nothing.
  • n = 1 returns -2147483648, and n = -2147483648 returns 1. The two are each other's reversal.
  • n = -2 returns 2147483647, the example where the sign bit goes from set to clear.
  • n = 2147483647 (0x7FFFFFFF) returns -2, because the 31 low ones move to bits 1 through 31 and bit 0 becomes 0.
  • A palindromic pattern such as 0x80000001 (that is -2147483647) returns itself.

Follow-ups interviewers ask

The function is called many times. How do you make it faster?
Cache the reversal of each byte in a 256-entry table. Then reverse a 32-bit value by looking up its four bytes and placing them in the opposite order: byte 0 reversed goes to the top, byte 3 reversed goes to the bottom. That is four lookups, a few shifts, and no loop. A 65536-entry table for 16-bit halves works the same way with two lookups, at the cost of more memory.
What if the input were 64 bits instead of 32?
The shift loop runs 64 rounds. The mask version adds one more level, swapping 32-bit halves first, then using 64-bit versions of the same masks. The idea and the O(1) cost per call do not change. Every constant and every type must widen to 64 bits.
Can you do it without a loop or a lookup table?
Yes, the five masked swaps do that. Each step swaps neighbouring blocks of size 16, 8, 4, 2, then 1. A bit at position p lands at 31 - p, which is p with all five index bits flipped, and each step flips exactly one index bit. There is no loop and no extra memory.

Reverse Bits FAQ

What is the time complexity of Reverse Bits?

It is O(1), because the word is always 32 bits. The shift loop does 32 rounds of constant work, and the mask-and-swap version does 5 steps. Space is O(1) as well. If the width were w bits, the loop would cost O(w) and the swap version O(log w).

Why use bit manipulation for Reverse Bits?

The problem is defined by bit positions, not by numeric value. Reading a bit with n & 1 and moving bits with shifts lets you place each bit directly at position 31 - p. Strings force you to handle padding and sign yourself, and they allocate memory for no gain.

How do you solve LeetCode 190 in Python?

Mask the input with n &= 0xFFFFFFFF. Run a loop 32 times doing result = (result << 1) | (n & 1) and n >>= 1. Then subtract 1 << 32 if result is at least 1 << 31. The mask and the final subtraction are needed because Python integers are unbounded.

How do you solve Reverse Bits in Java?

Java int is already 32-bit two's complement. Loop 32 times with result = (result << 1) | (n & 1) and use n >>>= 1 so no sign bits are copied in. Return result directly, because an int with bit 31 set is already negative. Integer.reverse(n) does the same thing in the standard library.

Why does Reverse Bits return a negative number for n = 1?

Reversal moves the lowest bit to position 31. In signed 32-bit two's complement, position 31 is the sign bit and is worth -2^31. A pattern with only that bit set is -2147483648.

Can Reverse Bits be solved in O(1) extra space?

Yes. The shift loop uses two integers, and the mask-and-swap version uses one. Even the string version uses only a fixed 32 characters, so every approach here is O(1) space.

Asked at

See which companies ask this — Pro

Practise it