Data Structures & AlgorithmsModerateCodeforces Div2 A · bit counting

Problem: What does the following print?

Problem: What does the following print?
print(sum(bin(i).count('1') for i in range(1, 16)))
  1. A. 28
  2. B. 30
  3. C. 24
  4. D. 32

Correct answer: D. 32

Each bit position 0 to 3 is set in exactly 8 of the numbers 0 to 15, so the bits from 1 to 15 contribute 4 * 8 = 32. Counting only the numbers with exactly 2 bits set gives a different total.

More Coding Interview Problems questions

Exams that ask this topic