loading

Reverse Bits — Step-by-Step Visualization

easyLeetCode #190Divide and ConquerBit Manipulation

Reverse bits of a given 32-bit unsigned integer.

Algorithm Pattern

Bitwise Shifting and Masking

Key Idea

To reverse bits of a 32-bit integer, we iterate 32 times. In each step, we shift the result to the left by 1, then we extract the rightmost bit of the input number (`n & 1`) and add it to the result (`res | (n & 1)`). Finally, we shift the input number to the right by 1 (`n >>= 1`). At the end, our result `res` will have the reversed bit sequence.

Step-by-Step Approach

  1. Initialize `res = 0`.
  2. Loop 32 times (from 0 to 31).
  3. Shift `res` left by 1: `res <<= 1`.
  4. Add rightmost bit of `n`: `res |= (n & 1)`.
  5. Shift `n` right by 1: `n >>= 1`.
  6. Wait, ensure unsigned handling for `res` using `>>> 0` in JS.

Common Gotchas

  • JavaScript's bitwise operators convert operands to 32-bit signed integers. Use `>>> 0` to convert the final signed result back to an unsigned 32-bit representation.

Related Problems