Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: How many 1-bits are set in 2^20 - 1?

Problem: How many 1-bits are set in 2^20 - 1?
print(bin(2 ** 20 - 1).count('1'))
What is printed?
  1. A. 20
  2. B. 1
  3. C. 21
  4. D. 2

Correct answer: A. 20

2²⁰ is 1 followed by 20 zeros, so 2²⁰ − 1 is exactly twenty 1-bits. Counting the bits of 2²⁰ itself gives 1, assuming 2²⁰ − 1 still has 21 bits gives 21, and writing 2 ^ 20 - 1 in Python is XOR (2 ^ 19 = 17 = 10001), which gives 2.

More Coding Interview Problems questions

Exams that ask this topic