Data Structures & AlgorithmsModerateCodeforces Div2 A · bit counting
Problem: What does the following print?
Problem: What does the following print?
print(sum(bin(i).count('1') for i in range(1, 16)))- A. 28
- B. 30
- C. 24
- D. 32
Correct answer: D. 32
Each bit position 0 to 3 is set in exactly 8 of the numbers 0 to 15, so the bits from 1 to 15 contribute 4 * 8 = 32. Counting only the numbers with exactly 2 bits set gives a different total.
More Coding Interview Problems questions
- Array a = [5, -3, 2, 4, -6, 1, 3, -2]. How many non-empty contiguous subarrays have a sum in the closed range [0, 4]?
- For the string s = "aabbabbaab", find the length of the longest substring with exactly as many letter a as letter b.
- For the array a = [4, 1, 7, 2, 2, 5, 3, 6], how many contiguous non-empty subarrays have XOR equal to 0? Use prefix XOR values.
- Array a = [3, 1, 4, 1, 5, 9, 2, 6]. How many subarrays of length exactly 3 have an even sum?
- Array a = [2, 4, 6, 1, 3, 5, 8, 7]. How many contiguous subarrays of length at least 2 have a sum divisible by 4?
- From the sorted side lengths [4, 6, 7, 9, 10, 13, 15], how many different triples (choosing distinct positions) can form a non-degenerate…