Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: How many integers from 1 to 10^6 have exactly one set bit (power of two)? Run the code.

Problem: How many integers from 1 to 10^6 have exactly one set bit (power of two)? Run the code.
print(sum(1 for x in range(1, 10 ** 6 + 1) if x & (x - 1) == 0))
What is printed?
  1. A. 19
  2. B. 20
  3. C. 7
  4. D. 1000

Correct answer: B. 20

2⁰ through 2¹⁹ = 524288 are ≤ 10⁶ and 2²⁰ = 1048576 is not, so 20. Forgetting 1 = 2⁰ gives 19, 7 counts powers of 10, and 1000 counts squares.

More Coding Interview Problems questions

Exams that ask this topic