GATE Computer ScienceHardGATE CS (PYQ pattern)

unsigned g(unsigned n) { return n ^ (n >> 1); } For which 8-bit n is g(n) == 0xB5? Give n in decimal.

  1. A. 239
  2. B. 181
  3. C. 155
  4. D. 217

Correct answer: D. 217

g is the Gray code. To invert it, each bit of n is the XOR of all bits of g(n) at that position and above: 0xB5 = 1011 0101 gives prefix XORs 1, 1, 0, 1, 1, 0, 0, 1, so n = 1101 1001 = 217. Applying g again (instead of its inverse) gives 239.

More Programming and Data Structures (GATE) questions

Exams that ask this topic