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?
- A. 5
- B. 4
- C. 6
- 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
- Problem: How many integers in [1, 100] are divisible by 7 or by 11? Run the code. python print(sum(1 for x in range(1, 101) if x % 7 == 0…
- Problem: What is 2^100 mod 7? Run the code. python print(pow(2, 100, 7)) What is printed?
- Problem: What is the length of the shortest path from node 1 to node 5 in the undirected graph with edges (1,2), (2,3), (1,4), (4,5)…
- Problem: How many connected components does the graph on vertices 0..5 with edges (0,1), (2,3), (4,5), (1,2) have? Run the union-find…
- Problem: Does the undirected graph with edges (0,1), (1,2), (2,0) contain a cycle? Run the union-find check and print 'cycle' or 'no…
- Problem: How many nodes are reachable from 0 in the directed graph with edges 0->1, 1->2, 3->0? Run the DFS code. python g = {0: [1], 1…