ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (>> is right shift, & is AND)

What will be the output of the following pseudocode? (>> is right shift, & is AND)
Integer a[3] = {4, 14, 2}, total = 0
for (each b from 0 to 3)
    Integer ones = 0
    for (each i from 0 to 2)
        ones = ones + ((a[i] >> b) & 1)
    end for
    total = total + ones * (3 - ones)
end for
Print total
  1. A. 6
  2. B. 2
  3. C. 4
  4. D. 8

Correct answer: A. 6

For each bit position, every (1, 0) pair of numbers differs there, giving ones × zeros pairs. 4 = 0100, 14 = 1110, 2 = 0010: bit 1 → 2 × 1, bit 2 → 2 × 1, bit 3 → 1 × 2. Total 6, the sum of Hamming distances over all pairs (2 + 2 + 2).

More Pseudocode and Code Tracing questions

Exams that ask this topic