The Problem

Reverse bits of a given 32-bit unsigned integer.

Note: In some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. This should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.

In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 below, the input represents the signed integer -3 and the output represents the signed integer -1073741825.

Interactive Visualization

Speed:
32-Bit Reversal Process
Input (n)
Decimal: 0
Press Step or Play to begin.
Output (result)
Decimal: 0
Current Step
Press Step or Play to begin.
Code
fun reverseBits(n: Int): Int {    var result = 0; var num = n    for (i in 0 until 32) {        val bit = num and 1        result = (result shl 1) or bit        num = num ushr 1    }    return result

How It Works

Key Insight

To reverse the bits, we extract bits from the right side of the input (least significant bit first) and build the result from right to left by shifting and placing each bit. This effectively reverses the entire 32-bit sequence. We use bitwise operations: & to extract, << to shift left, | to place bits, and >> to shift right.

The Algorithm

  • Initialize result = 0. This will hold our reversed bits.
  • For each of the 32 bits (i = 0 to 31):
  • โ€” Extract the rightmost bit from n using bit = n & 1.
  • โ€” Shift result left by 1 position: result = result << 1.
  • โ€” Place the bit in the rightmost position of result: result = result | bit.
  • โ€” Shift n right by 1 position: n = n >> 1.
  • After 32 iterations, result contains all bits of n in reverse order.

Complexity

Time O(1)
Space O(1)

The algorithm always performs exactly 32 iterations (one per bit), regardless of the input value. Each iteration uses a constant amount of bitwise operations. Therefore, both time and space complexity are O(1).