Skip to main content

🟩 Reverse Bits (#190)

📋 Problem Statement

Reverse bits of a given 32 bits unsigned integer.

💡 Examples

Example 1

Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)

Example 2

Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)

🔑 Key Insights & Approach

Core Observation: Build result by extracting rightmost bit of n and adding to leftmost position of result.

Why Bit-by-Bit?

  • O(32) = O(1) time
  • Extract each bit and place in reversed position
  • Simple and efficient

Pattern: "Bit Reversal" pattern.

🐍 Solution: Python

Approach: Bit-by-Bit

Time Complexity: O(1) | Space Complexity: O(1)

class Solution:
def reverseBits(self, n: int) -> int:
result = 0

for i in range(32):
bit = (n >> i) & 1
result |= (bit << (31 - i))

return result

Approach 2: Shift and Build

Time Complexity: O(1) | Space Complexity: O(1)

class Solution:
def reverseBits(self, n: int) -> int:
result = 0

for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1

return result

🔵 Solution: Golang

Approach: Bit-by-Bit

Time Complexity: O(1) | Space Complexity: O(1)

func reverseBits(num uint32) uint32 {
var result uint32

for i := 0; i < 32; i++ {
bit := (num >> i) & 1
result |= (bit << (31 - i))
}

return result
}

📚 References