Typorithm · easy

Reverse Bits

▷ Interactive algorithm labreverse-bitsbit-manipulationshiftbuild-upunsigned
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Reverse Bits

0%

Bit Manipulation

Pull n's lowest bit and push it into result, shifting both, for all 32 bits.

Reversing bits builds the output one bit at a time from the input's low end.

Each step shifts result left to make room, then ORs in the lowest bit of n.

Using the unsigned shift >>> avoids JavaScript's signed 32-bit quirks.

Preparing algorithm lab…
01

Shift result left, OR in n & 1.

02

Use >>> for unsigned shifts.

03

Run exactly 32 times.

function reverseBits(n) {
  let result = 0;

  for (let i = 0; i < 32; i += 1) {
    result = (result << 1) | (n & 1);
    n = n >>> 1;
  }

  return result >>> 0;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. All 32 bits

Process every bit of a 32-bit integer.

for (let i = 0; i < 32; i += 1)

2. Shift in low bit

Make room in result, then append n's lowest bit.

result = (result << 1) | (n & 1)

3. Drop low bit

Unsigned right shift discards the bit just read.

n = n >>> 1

4. Force unsigned

>>> 0 reinterprets the result as an unsigned 32-bit value.

return result >>> 0

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Reverse Bits: Visual Walkthrough & Practice · Typorithm | ApplyDjinn