Data Structures & AlgorithmsModerateTCS NQT · bit counting
Problem: How many set bits are there in total across the numbers 0 to 7? Run the code.
Problem: How many set bits are there in total across the numbers 0 to 7? Run the code.
print(sum(bin(i).count('1') for i in range(8)))What is printed?- A. 8
- B. 7
- C. 9
- D. 12
Correct answer: D. 12
Each of the 3 bit positions is set in 4 of the 8 numbers, giving 3 * 4 = 12.
More Coding Interview Problems questions
- Problem: How many integers in [1, 20] are powers of two? Run the code. python print(sum(1 for x in range(1, 21) if x & (x - 1) == 0)) What…
- 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…