sagelearnai

Reverse Bits

Difficulty: Easy · Pattern: Bit Manipulation · LeetCode #190

Reverse the bits of a 32-bit unsigned integer n and return the result as an unsigned integer.

Examples

text
n = 43261596   (00000010100101000001111010011100)
→ 964176192    (00111001011110000010100101000000)
n = 4294967293 (11111111111111111111111111111101)
→ 3221225471   (10111111111111111111111111111111)

Hints

  1. Repeat 32 times: take the lowest bit of n and push it into the result from the right.
  2. In JavaScript, bitwise operations produce signed 32-bit numbers. Use >>> 0 to read the result as unsigned.

Approach

text
res = 0
repeat 32: res = (res << 1) | (n & 1); n >>= 1

Language pitfalls: in JS, << can make the value negative once bit 31 is set, so finish with res >>> 0, and shift n with >>>, not >>. Python integers are unbounded, so there's no overflow, but you must loop exactly 32 times to place the bits correctly.

Follow-up (called many times): the divide-and-conquer swap reverses in 5 steps (swap halves, then bytes, nibbles, pairs, bits using the masks 0x55555555, 0x33333333, …), or use a lookup table of reversed bytes.

Complexity

Time: O(32). Space: O(1).

Python solution
def reverseBits(n):
    res = 0
    for _ in range(32):
        res = (res << 1) | (n & 1)
        n >>= 1
    return res
JavaScript solution
function reverseBits(n) {
  let res = 0;
  for (let i = 0; i < 32; i++) {
    res = (res << 1) | (n & 1);
    n >>>= 1;
  }
  return res >>> 0;
}