ProgrammingVery hardAmazon OA · Goldman Sachs OA

What will be the output of the following pseudocode? (^ is XOR, & is AND; x & (−x) keeps the lowest 1-bit)

What will be the output of the following pseudocode? (^ is XOR, & is AND; x & (−x) keeps the lowest 1-bit)
Integer a[6] = {2, 4, 7, 9, 2, 4}
Integer x = 0, low, p = 0, q = 0
for (each i from 0 to 5)
    x = x ^ a[i]
end for
low = x & (-x)
for (each i from 0 to 5)
    if ((a[i] & low) != 0)
        p = p ^ a[i]
    else
        q = q ^ a[i]
    end if
end for
Print x, p, q
  1. A. 0 7 9
  2. B. 14 7 9
  3. C. 14 9 7
  4. D. 16 7 9

Correct answer: B. 14 7 9

Pairs cancel, so x = 7 ^ 9 = 14 (1110). Its lowest set bit is 2, which splits the numbers: those with bit 2 (2, 7, 2) XOR to 7, the rest (4, 9, 4) XOR to 9. Output 14 7 9.

More Pseudocode and Code Tracing questions

Exams that ask this topic