Question presented to candidate: "Walk me through the bit manipulation tricks you would actually use in a coding interview. For each, tell me the expression, why it works, and anything about Python integers that changes how you write it."
What a strong answer should cover:
- The single-bit operations with a mask: test
(x >> i) & 1, setx | (1 << i), clearx & ~(1 << i), togglex ^ (1 << i). - The lowest-set-bit pair:
x & (x - 1)clears it,x & -xisolates it; the power-of-two test with thex > 0guard. - XOR properties (
a ^ a == 0,a ^ 0 == a) and their uses: single number, missing number, Hamming distance. - Bitmasks as sets: enumerate subsets with
range(1 << n), submasks withsub = (sub - 1) & mask, and the 3^n total. - Python details: ints are unbounded (no overflow, no
>>>), negatives act like infinite leading 1s so you mask with& 0xFFFFFFFFto emulate 32 bits,int.bit_count()(3.10+) andint.bit_length(), and&binds tighter than==in Python (unlike C-family languages).
Code / implementation expected: Optional โ short Python expressions for each trick, ideally with a small demo on one number.