Data Structures & AlgorithmsModerateTCS CodeVita · Microsoft SDE OA

In the reflected binary Gray code, the number with index i is i XOR (i >> 1). Using 0-based indices, what is the value printed for i = 5 by the following code?

In the reflected binary Gray code, the number with index i is i XOR (i >> 1). Using 0-based indices, what is the value printed for i = 5 by the following code?
i=5
print(i^(i>>1))
What is printed?
  1. A. 7
  2. B. 15
  3. C. 2
  4. D. 4

Correct answer: A. 7

Gray code is i XOR (i >> 1); for i = 5 (101) the shifted value is 010, so 101 XOR 010 = 111. A left shift, a plain right shift, or the popcount each produces a different value.

More Coding Interview Problems questions

Exams that ask this topic