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?
- A. 19
- B. 20
- C. 7
- 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
- Problem: What is the maximum number of points on a line among (0,0), (1,1), (2,2), (3,5), (4,4) (collinear with the diagonal)? Run the…
- Problem: What is the time complexity of the Hopcroft-Karp algorithm for maximum matching on V vertices and E edges?
- Problem: Which technique gives the answer to 'minimum number of platforms' by sorting events?
- Problem: Which of these is the standard O(n log n) algorithm for the longest increasing subsequence?
- Problem: What is the standard complexity of computing all pairs of shortest paths in a graph with V vertices using repeated squaring of…
- Problem: Which result says that every planar graph is 5-colourable?