What does the expression n & (n - 1) do at the bit level, and what problems does that one operation let you solve cheaply?

technical-conceptual · Mid level · software-engineering

What the interviewer is really asking

Probes whether the candidate can reason precisely about what n & (n-1) does to the binary representation, derive the power-of-two and bit-count uses from it, and apply judgment about when a bit trick is worth the readability cost.

What to say

What to avoid

Example answers

Strong: I needed a fast population count over millions of permission bitmasks. Instead of looping all 64 bit positions per mask, I used n &= n - 1 to strip one set bit per iteration, so the loop ran once per set bit — far fewer iterations on sparse masks — and where the platform had it I used the hardware popcount built-in instead.

Weak: I think n & (n - 1) is some trick for powers of two — I'd have to look up exactly what it does.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.