Data Structures & AlgorithmsModerateTCS NQT · bit counting

Problem: How many set bits are there in total across the numbers 0 to 7? Run the code.

Problem: How many set bits are there in total across the numbers 0 to 7? Run the code.
print(sum(bin(i).count('1') for i in range(8)))
What is printed?
  1. A. 8
  2. B. 7
  3. C. 9
  4. D. 12

Correct answer: D. 12

Each of the 3 bit positions is set in 4 of the 8 numbers, giving 3 * 4 = 12.

More Coding Interview Problems questions

Exams that ask this topic