Data Structures & AlgorithmsModerateCodeforces Div2 B · bit counting

Problem: What is the sum over all pairs (i < j) of the Hamming distances (number of differing bits) between the values in [1, 3, 5]? Run the code.

Problem: What is the sum over all pairs (i < j) of the Hamming distances (number of differing bits) between the values in [1, 3, 5]? Run the code.
a = [1, 3, 5]
print(sum(bin(a[i] ^ a[j]).count('1') for i in range(len(a)) for j in range(i + 1, len(a))))
What is printed?
  1. A. 3
  2. B. 5
  3. C. 6
  4. D. 4

Correct answer: D. 4

1 XOR 3 = 2 (one bit), 1 XOR 5 = 4 (one bit) and 3 XOR 5 = 6 (two bits), giving 4. The sum of XOR values is a different quantity.

More Coding Interview Problems questions

Exams that ask this topic