#190

Reverse Bits

Easy Shifts

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Reverse the order of the 32 bits of an integer.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: mirror the 32-bit pattern.

Why this works: take the last bit of n and push it onto the right of the result, 32 times. Leading zeros become trailing zeros.

Example (4 bits for short): n = 0011

step1: result 1,    n 001step2: result 11,   n 00step3: result 110,  n 0step4: result 1100

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Stopping when n becomes 0. Leading zeros still need to become trailing zeros, so always run all 32 steps.