Given a number N, write a function which generates all n-bit gray code sequences, a gray code sequence is a sequence such that successive patterns in it differ by one bit
belongs to collection: Interview C++ coding problems/challenges | Coding Algorithms
All Answers
total answers (1)
Construction an n bit gray code follows a robust algorithm. The binary-reflected Gray code list for n bits can be generated recursively from the list for n − 1 bits by reflecting the list (i.e. listing the entries in reverse order), prefixing the entries in the original list with a binary 0, prefixing the entries in the reflected list with a binary 1, and then concatenating the original list with the reversed list.
Reference: Gray_code
Algorithm to generate n bit gray code list
For any n bit gray code list, we start with gray code list of length 1 (elements are only '0' and '1'). Then iterate till finding n-bit gray code list.
The above can be explained with help of an example,
C++ implementation
Output