Skip to the page

Bits and string matching · mid

Bit tricks in JavaScript

JavaScript bitwise operators work on 32-bit signed integers, and a few tricks—x & (x − 1) clears the lowest set bit, XOR cancels pairs, masks store sets of flags—solve the bit questions that frontend rounds ask.

The notes

What you must know

  • Operands are converted to 32-bit signed integers: values above 2^31 − 1 wrap. Use >>> 0 to read as unsigned; use BigInt for 64-bit work.
  • x & 1 tests odd/even; x & (x − 1) clears the lowest set bit (count bits by repeating it); a power of two has exactly one bit: x > 0 && (x & (x − 1)) === 0.
  • XOR: a ^ a = 0 and a ^ 0 = a, so XOR of all numbers leaves the one that appears once.
  • Flags and permissions: READ = 1, WRITE = 2, ADMIN = 4; has = (mask & FLAG) !== 0; add = mask | FLAG; remove = mask & ~FLAG. React uses bit flags for lanes and fiber flags.
  • Subsets by mask: for mask from 0 to 2^n − 1, bit i set means item i is included.
  • x | 0 truncates toward zero but breaks above 2^31; prefer Math.trunc.

The red pen

Common traps: mistake → fix

  • Mistake: x | 0 is a safe integer cast

    Fix: (2 ** 31) | 0 is -2147483648.

  • Mistake: ~x is 'not x' as a boolean

    Fix: it is −x − 1.

  • Mistake:

    and >>> are the same

    Fix:

    keeps the sign; >>> fills with zeros.

Easy to hard

Questions interviewers ask, easy to hard

  1. Find the single number when every other appears twice.
  2. Count set bits of a number.
  3. Check whether n is a power of two.
  4. Store and check user permissions as bit flags.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview