Pattern — Bit Tricks

Cheat sheet

TrickCodeUse case
Check bit i(x >> i) & 1Test
Set bit ix | (1 << i)Mark
Clear bit ix & ~(1 << i)Unmark
Toggle bit ix ^ (1 << i)Flip
Lowest set bitx & -xIsolate LSB
Clear lowest set bitx & (x-1)Count bits
Power of 2?x > 0 && (x & (x-1)) === 0LC #231
Number of bits`(x.toString(2).match(/1/g)
All bits XORa ^ b ^ b = aSingle number
Swap without tempa^=b; b^=a; a^=bTrick
Power of 4?x > 0 && (x & (x-1)) === 0 && (x & 0x55555555) !== 0LC #342

JS pitfalls (cực quan trọng)

>>> vs >> trong JavaScript

  • >>arithmetic shift — giữ dấu (cho số âm thành rất lớn).
  • >>>logical shift — chèn 0 từ trái.
  • Khi đếm bits của uint32 (vd LC #190 reverse bits, #191 count bits), PHẢI dùng >>>.
// SAI:
function countBits(n: number): number {
  let count = 0;
  while (n) { count += n & 1; n >>= 1; }   // n âm → vô hạn loop!
  return count;
}
 
// ĐÚNG:
function countBits(n: number): number {
  let count = 0;
  while (n) { count += n & 1; n >>>= 1; }  // logical shift
  return count;
}

Top problems

BàiLCTrick
Single NumberLC #136XOR all
Single Number IILC #137State machine 3 mod
Single Number IIILC #260XOR + lowest set bit để partition
Number of 1 BitsLC #191Brian Kernighan x & (x-1)
Counting BitsLC #338DP dp[i] = dp[i>>1] + (i&1)
Power of TwoLC #231x & (x-1) === 0
Missing NumberLC #268XOR [0..n] ^ nums
Reverse BitsLC #190Loop 32 lần với >>>
Sum of Two IntegersLC #371a^b + (a&b)<<1 (carry)
Maximum XORLC #421Trie of bits
Bitwise AND of RangeLC #201Common prefix

Bitmask DP

Khi state có phần tử, lưu state vào 1 bitmask . Vd:

  • TSP / Hamiltonian (LC #847, #943)
  • Partition into K Equal Subsets (LC #698)
  • Minimum Cost to Connect Points (subset DP)

→ Nguồn: 02-Bit-Manipulation, 10-Advanced-DP (Bitmask DP section)