ProgrammingHardTCS NQT · Infosys · Capgemini

What will be the output of the following pseudocode? (^ is bitwise XOR, & is bitwise AND, >> is a right shift; all values are non-negative integers.)

What will be the output of the following pseudocode? (^ is bitwise XOR, & is bitwise AND, >> is a right shift; all values are non-negative integers.)
Integer n = 156
Integer g = n ^ (n >> 2)
Integer h = g
Integer r = 0
While g > 0
    r = r + (g & 1)
    g = g >> 1
End While
Print h, r
  1. A. 210 4
  2. B. 143 5
  3. C. 187 6
  4. D. 4 1

Correct answer: C. 187 6

156 = 10011100 in binary and 156 >> 2 = 00100111 (39); XOR gives 187 (10111011), which has 6 one-bits. The loop only counts set bits, and h keeps the value of g from before it is shifted away.

More Pseudocode and Code Tracing questions

Exams that ask this topic