Data Structures & AlgorithmsModerateTCS NQT · Product Company OA

Problem: What is the total number of 1-bits in the binary representations of 1 through 10? Run the code.

Problem: What is the total number of 1-bits in the binary representations of 1 through 10? Run the code.
print(sum(bin(i).count('1') for i in range(1, 11)))
What is printed?
  1. A. 15
  2. B. 19
  3. C. 21
  4. D. 17

Correct answer: D. 17

Popcounts of 1..10 are 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, which add up to 17. Stopping at 9 (dropping 10 = 1010, two bits) gives the tempting 15; range(1, 11) includes 10.

More Coding Interview Problems questions

Exams that ask this topic