Use XOR, masks, and shifts to work with bits directly.
Reach for it when
Single number among pairs (XOR cancels)
Count set bits, reverse bits
Add without the + operator
Core idea
x ^ x = 0 and x ^ 0 = x, so XOR-ing everything cancels pairs. n & (n - 1) clears the lowest set bit, which counts bits in O(set bits). Addition is XOR (sum without carry) plus AND shifted left (the carry), repeated until no carry remains.
Template · O(number of bits)
defcount_bits(n):
count =0
while n:
n &= n -1# drop the lowest set bit
count +=1
return count
intcountBits(uint32_tn) {
int count =0;
while (n) {
n &= n -1; // drop the lowest set bit
count++;
}
return count;
}
Common pitfalls
Python integers are unbounded: mask with 0xFFFFFFFF for 32-bit behavior
Operator precedence: wrap bit expressions in parentheses