Skip to content

Reverse Bits

Easy Day 3 • Striver Blind 75

Reverse bits of a given 32-bits unsigned integer.

Example 1:

  • Input: n = 43261596
  • Output: 964176192

Constraints:

  • Input must be a 32-bit unsigned integer

Extract last bit of n, shift result left, shift n right, 32 times.

Bit Shifting Loop


📊 Step-by-Step Execution (Mermaid Diagram)

Section titled “📊 Step-by-Step Execution (Mermaid Diagram)”
graph TD
A["Input Integer / Bits"] --> B["Apply Bitwise Operation (AND / XOR / Shift)"]
B --> C{"Check Bit Condition"}
C -- "Condition Met" --> D["Update Bit Count / Result"]
C -- "Continue" --> E["Shift Bits (>>> 1 or & n-1)"]
E --> B
D --> F["Return Final Result"]

function reverseBits(n) {
let res = 0;
for (let i = 0; i < 32; i++) {
res = (res << 1) | (n & 1);
n >>>= 1;
}
return res >>> 0;
}
  • Time Complexity: O(32)
  • Space Complexity: O(1)
  • Explanation: 32 bit shifts.

function reverseBits(n) {
let res = 0;
for (let i = 0; i < 32; i++) {
res = (res << 1) | (n & 1);
n >>>= 1;
}
return res >>> 0;
}
  • Time Complexity: O(32)
  • Space Complexity: O(1)
  • Explanation: Bitwise reverse using bit shift.

  1. Initialize State: Setup necessary pointers, dynamic programming arrays, or hash maps.
  2. Iterate & Evaluate: Process the input according to the boundary conditions.
  3. Update & Return: Compute the optimal answer and return early or at termination.

Iterate 32 times, extracting lowest bit of n and adding it to res.


  1. Process all 32 bits from right to left.

👉 Solve this problem interactively in the DSA Lab