Data Structures & AlgorithmsModerateTCS NQT · bit tricks

Problem: How many integers in [1, 20] are powers of two? Run the code.

Problem: How many integers in [1, 20] are powers of two? Run the code.
print(sum(1 for x in range(1, 21) if x & (x - 1) == 0))
What is printed?
  1. A. 5
  2. B. 4
  3. C. 6
  4. D. 3

Correct answer: A. 5

The powers of two in range are 1, 2, 4, 8 and 16. The test x & (x - 1) == 0 detects exactly these values.

More Coding Interview Problems questions

Exams that ask this topic