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?- A. 20
- B. 1
- C. 21
- 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
- Problem: What is the maximum sum of a contiguous subarray of exactly length 3 in [5, -2, 7, 1, 0, 4]? python a = [5, -2, 7, 1, 0, 4]…
- Problem: How many subsets of {1, 2, ..., 10} contain no two consecutive integers? python from itertools import combinations print(sum(1…
- Problem: How many integers in [1, 1000] are perfect squares or perfect cubes? python print(sum(1 for x in range(1, 1001) if any(k k == x…
- Problem: Greedy graph colouring assigns colours in vertex order 0, 1, 2, 3, 4, 5, giving each vertex the smallest colour (starting at 0)…
- Problem: In the undirected graph with edges 0-1, 0-2, 1-2, 1-3, 2-3, 3-4, how many simple paths (no repeated vertex) go from vertex 0 to…
- Problem: An undirected forest (a graph with no cycles) has 9 vertices and 6 edges. How many connected components does it have?