ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? ((mask >> i) & 1 is evaluated before ==; ^ is XOR)

What will be the output of the following pseudocode? ((mask >> i) & 1 is evaluated before ==; ^ is XOR)
Integer a[3] = {5, 1, 6}, total = 0
for (each mask from 0 to 7)
    Integer x = 0
    for (each i from 0 to 2)
        if ((mask >> i) & 1 == 1)
            x = x ^ a[i]
        end if
    end for
    total = total + x
end for
Print total
  1. A. 24
  2. B. 28
  3. C. 12
  4. D. 48

Correct answer: B. 28

total adds the XOR of every subset. A bit contributes 2^(bit) × 2ⁿ⁻¹ whenever at least one element has it: the OR is 5 | 1 | 6 = 7, so total = 7 × 2² = 28.

More Pseudocode and Code Tracing questions

Exams that ask this topic