Gray code

By | January 3, 2016
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

The original problem is from leetcode: https://leetcode.com/problems/gray-code/

And I found a very good solution from Wolfram: The code is called reflected because it can be generated in the following manner. Take the Gray code 0, 1. Write it forwards, then backwards: 0, 1, 1, 0. Then prepend 0s to the first half and 1s to the second half: 00, 01, 11, 10. Continuing, write 00, 01, 11, 10, 10, 11, 01, 00 to obtain: 000, 001, 011, 010, 110, 111, 101, 100, … (OEIS A014550). Each iteration therefore doubles the number of codes.

graycode

In this way, the problem can be solved in linear time.

Chek my code on github: link