Predict the output
What does this print?
x = 12
steps = []
while x:
x &= x - 1
steps.append(bin(x))
print(steps, (12).bit_count())Choose an answer, then open Show answer below to check it.
Show answer
Answer: A ['0b1000', '0b0'] 2
Right: 1100 loses its lowest 1 bit twice, so it has two 1 bits.
The loop runs once per 1 bit rather than once per bit position, which matters for sparse numbers.
Why not the others?
- B ['0b1011', '0b1010'] 2. Those are x - 1 values; the & keeps only bits set in both.
- C ['0b110', '0b11', '0b1', '0b0'] 2. That is shifting right, not clearing bits.