ProgrammingVery hardProduct company OA · code-tracing level

What will be the output of the following pseudocode? (^ is bitwise XOR and >> is a right shift.)

What will be the output of the following pseudocode? (^ is bitwise XOR and >> is a right shift.)
Integer g = 59, n = 0
while (g > 0)
    n = n ^ g
    g = g >> 1
end while
Print n
  1. A. 45
  2. B. 59
  3. C. 29
  4. D. 54

Correct answer: A. 45

n becomes g ^ (g >> 1) ^ (g >> 2) ^ …, which decodes a Gray code: each bit of n is the XOR of all bits of g at or above it. g = 59 = 111011. From the top: 1, 1⊕1 = 0, 0⊕1 = 1, 1⊕0 = 1, 1⊕1 = 0, 0⊕1 = 1 → 101101 = 45. (Check: 45 ^ (45 >> 1) = 101101 ^ 010110 = 111011 = 59.) 29 = 59 >> 1 is only the first shift; 54 comes from XOR-ing just g and g >> 1 and then shifting.

More Pseudocode and Code Tracing questions

Exams that ask this topic