Data Structures & AlgorithmsHardCodeforces Div2 B · bit counting

Problem: What is the sum of the number of 1-bits in the binary representations of 1, 2, ..., 20? Run the code.

Problem: What is the sum of the number of 1-bits in the binary representations of 1, 2, ..., 20? Run the code.
print(sum(bin(i).count('1') for i in range(1, 21)))
What is printed?
  1. A. 40
  2. B. 42
  3. C. 38
  4. D. 44

Correct answer: B. 42

Summing popcount over 1..20 gives 42. Using a 2-to-the-bits shortcut that counts only up to 16 misses the bits of 17 to 20.

More Coding Interview Problems questions

Exams that ask this topic