synopsis · Paradigms · chapter 34
Bit Manipulation
10 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A Java
intis 32 bits in two's complement.&,|,^,~,<<,>>,>>>work on all 32 at once, in O(1). - template
With
m = 1 << k: check(x & m) != 0· setx | m· clearx & ~m· togglex ^ m. - pro tip
x & (x − 1)erases the lowest 1-bit (popcount, power of two).x & -xkeeps only the lowest 1-bit (Single Number III). - use it when
"Twice except one", "missing from 0..n", "without + or −", "power of two", "all subsets" with n ≤ 20 → think bits.
- pro tip
XOR:
a ^ a = 0,a ^ 0 = a, any order. XOR everything and every pair cancels, in O(1) space. - cost
One operator: O(1). A loop over a value's bits: O(log V) ≤ 32. All subsets by mask: O(n·2ⁿ). Every submask of every mask: O(3ⁿ).
- trap
==binds tighter than&: write(x & m) != 0. And(x & m) == 1is only right for bit 0. - trap
1 << 32 == 1(the shift is taken mod 32): use1L << kfor long masks.>>keeps the sign; use>>>for raw bits. - trap
One extra negative:
-Integer.MIN_VALUE == Integer.MIN_VALUE. A power-of-two test needsn > 0first. - pro tip
Binary numbers as long strings: add column by column from the right with a carry.
Integer.parseInt(s, 2)overflows past 31 digits.
Shaky on a card? Open the chapter or flip its recall cards.