Question presented to candidate: "Write a Python function that returns the number of 1 bits in an integer. Start simple, then make it faster, and tell me what your function returns for a negative number."
What a strong answer should cover:
- The naive loop over 32 bit positions, then Brian Kernighan's
n &= n - 1, which runs once per set bit. - Constant-time options: a 256-entry byte table, or the parallel SWAR additions.
- Complexity: O(32) vs O(number of set bits) vs O(1), and the O(n) DP
bits[i] = bits[i >> 1] + (i & 1)for every number 0..n. - Python details:
int.bit_count()(Python 3.10+) andbin(n).count("1"); Python ints are unbounded, so a negative number has no fixed bit pattern:while n: n &= n - 1never ends for negative n, and you mask withn & 0xFFFFFFFFto get the 32-bit answer.
Clarifying questions expected:
- How should negative numbers be treated: as 32-bit two's complement, or by magnitude?
- Is this one call, or many calls (or every number up to n)?
Code / implementation expected: Yes โ Kernighan's loop in Python 3 with a 32-bit mask, plus the built-in int.bit_count().