ProgrammingHardProduct company OA

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

What will be the output of the following pseudocode? (^ is bitwise XOR, & is AND, >> is a right shift.)
Integer x = 29, y = 30
Integer gx = x ^ (x >> 1)
Integer gy = y ^ (y >> 1)
Integer d = gx ^ gy, bits = 0
while (d > 0)
    bits = bits + (d & 1)
    d = d >> 1
end while
Print gx, gy, bits
  1. A. 19 17 1
  2. B. 19 17 2
  3. C. 14 15 1
  4. D. 29 30 2

Correct answer: A. 19 17 1

x ^ (x >> 1) is the Gray code. 29 = 11101, 29 >> 1 = 01110 → 10011 = 19. 30 = 11110, 30 >> 1 = 01111 → 10001 = 17. 19 ^ 17 = 00010 has one set bit: consecutive numbers' Gray codes always differ in exactly one bit, while 29 and 30 themselves differ in two bits.

More Pseudocode and Code Tracing questions

Exams that ask this topic