ProgrammingHardAmazon OA · Infosys SP

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

What will be the output of the following pseudocode? (^ is XOR, & is AND, >> is right shift)
Integer x = 21, z = 22
Integer y = x ^ (x >> 1)
Integer w = z ^ (z >> 1)
Print y, (y & (y + 1)) == 0, (w & (w + 1)) == 0
  1. A. 31 false true
  2. B. 31 true false
  3. C. 15 true true
  4. D. 29 true true

Correct answer: B. 31 true false

If the bits of x alternate (21 = 10101), x ^ (x >> 1) is all 1's (11111 = 31), and then y & (y + 1) = 0. For 22 = 10110 the bits do not alternate: w = 10110 ^ 01011 = 11101 = 29, and 29 & 30 ≠ 0. Output 31 true false.

More Pseudocode and Code Tracing questions

Exams that ask this topic