#190

Reverse Bits

Easy
Divide and ConquerBit ManipulationBit ManipulationTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution uses bit manipulation to reverse the bits directly without converting to a string. This is more efficient and avoids unnecessary overhead.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a variable to hold the reversed bits.
  2. 2Step 2: For each of the 32 bits, extract the least significant bit from n and add it to the reversed variable.
  3. 3Step 3: Shift n right by 1 and the reversed variable left by 1.
  4. 4Step 4: Repeat this for all 32 bits.
solution.py8 lines
1# Full working Python code
2
3def reverseBits(n):
4    result = 0
5    for _ in range(32):
6        result = (result << 1) | (n & 1)
7        n >>= 1
8    return result

Complexity note: This is constant time complexity because we always perform a fixed number of operations (32) regardless of the input value.

  • 1Bit manipulation can be more efficient than string manipulation.
  • 2Understanding how to manipulate bits directly is crucial for optimizing performance.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.