Bit Manipulation — Master Recap & Cheatsheet
Advertisement
Bit Manipulation Master Cheatsheet
Essential Tricks
n & (n-1) # Remove lowest set bit (Brian Kernighan)
n & (-n) # Isolate lowest set bit
n | (n-1) # Set all bits below lowest 1
~n + 1 # Two's complement (negation)
n ^ n == 0 # XOR self = 0 (cancel duplicates)
n ^ 0 == n # XOR with 0 = identity
x ^ y == 0 iff x==y # Equality check via XOR
(n >> i) & 1 # Get bit i
n | (1 << i) # Set bit i
n & ~(1 << i) # Clear bit i
n ^ (1 << i) # Toggle bit i
n & (n-1) == 0 and n > 0 # Power of 2 check
XOR Properties Summary
| Property | Expression |
|---|---|
| Self-cancel | a ^ a = 0 |
| Identity | a ^ 0 = a |
| Commutative | a ^ b = b ^ a |
| Associative | (a^b)^c = a^(b^c) |
| Find missing | XOR all expected + actual |
| Find single | XOR all (duplicates cancel) |
Bitmask DP Template
dp = [inf] * (1 << n)
dp[0] = 0
for mask in range(1 << n):
i = bin(mask).count('1') # number of assigned items
for j in range(n):
if not (mask & (1 << j)): # j not yet used
new_mask = mask | (1 << j)
dp[new_mask] = min(dp[new_mask], dp[mask] + cost(i, j))
Subset Enumeration Template
sub = mask
while sub:
process(sub)
sub = (sub - 1) & mask # next smaller subset of mask
Language Popcount
# Python
bin(n).count('1')
# C/C++
__builtin_popcount(n)
# Java
Integer.bitCount(n)
# JavaScript
n.toString(2).split('').filter(x=>x==='1').length
Problem Index
| Pattern | Problems |
|---|---|
| XOR cancel | Single Number I (01), Missing Number (07), Single Number III (03) |
| 3-state bits | Single Number II (02) |
| Brian Kernighan | Number of 1 Bits (04) |
| Bit DP | Counting Bits (05) |
| Bitmask enumerate | Subsets (09), Product Word Lengths (17), DNA Sequences (15) |
| Bitmask DP | Partition K Subsets (10), Min XOR Sum (13), Valid Words Puzzle (16) |
| Bit tricks | Sum without + (08), Reverse Bits (06), Gray Code (14), Bitwise AND Range (12) |
Advertisement