Reverse Bits - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

  • We want to reverse the bits of the 32-bit signed integer provided in the parameter n. To do this, we construct the reversed number bit-by-bit in a variable res, starting from 0. We update n at each step so that it always reflects the remaining bits still to be extracted.
  • Main idea:
    Because the input is a 32-bit integer, we must process all 32 bits — including any leading zeros — to form the correctly reversed 32-bit result. In each of the 32 iterations, we:
    • Shift res left by 1 to make room for the next bit.
    • Take the last bit of n using n & 1.
    • Place that extracted bit at the end of res using res = (res << 1) | (n & 1).
    • Right shift n by 1 to remove the used bit.
    By the end of 32 iterations, res contains the fully reversed 32-bit pattern so we return it.
  • Why the formula works:
    • res << 1 shifts existing bits left and places a guaranteed 0 at the end.
    • n & 1 extracts the last bit of n (the bit to place).
    • | correctly inserts this bit, because x | 0 = x and x | 1 = 1.

Time Complexity

The loop always runs for exactly 32 iterations, regardless of the input value. Each iteration performs only constant-time bitwise operations. Therefore, the overall time complexity is O(1).

Space Complexity

We maintain only two integers (n and res) and use no additional data structures. Therefore, the space complexity is O(1).

Visucodize editorial solution titled JS Solution for LeetCode's Reverse Bits coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/reverse-bits.