![]() |
VOOZH | about |
Given a number n, generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit.
Examples:
Input: n=2
Output: 00 01 11 10
Explanation:
Every adjacent element of gray code differs only by one bit. So the n bit grey codes are: 00 01 11 10Input: n=3
Output: 000 001 011 010 110 111 101 100
Explanation:
Every adjacent element of gray code differs only by one bit. So the n bit gray codes are: 000 001 011 010 110 111 101 100
Another approach of Generate n-bit Gray Codes has already been discussed.
The idea is to get gray code of binary number using XOR and Right shift operation.
In this way, the gray code can be calculated for the corresponding binary number. So, it can be observed that the ith element can be formed by bitwise XOR of i and floor(i/2) which is equal to the bitwise XOR of i and (i >> 1) i.e., i right-shifted by 1. By performing this the MSB of the binary number is kept intact and all the other bits are performed bitwise XOR with its adjacent higher bit.
000 001 011 010 110 111 101 100
Complexity Analysis: