Data Structures & AlgorithmsModerateICPC regional · bit manipulation

Problem: What does the following print?

Problem: What does the following print?
print([format(i ^ (i >> 1), '03b') for i in range(4)])
  1. A. ['000', '001', '010', '011']
  2. B. ['000', '010', '011', '001']
  3. C. ['000', '001', '011', '010']
  4. D. ['001', '000', '011', '010']

Correct answer: C. ['000', '001', '011', '010']

i XOR (i >> 1) is the reflected Gray code, so consecutive values differ in one bit: 000, 001, 011, 010. Printing plain binary is the trap.

More Coding Interview Problems questions

Exams that ask this topic