Generate n | C ++ program to generate n - bit gray codes ; Function to convert decimal to binary ; leftmost digits are filled with 0 ; Function to generate gray code ; generate gray code of corresponding binary number of integer i . ; printing gray code ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void decimalToBinaryNumber ( int x , int n ) { int * binaryNumber = new int ( x ) ; int i = 0 ; while ( x > 0 ) { binaryNumber [ i ] = x % 2 ; x = x / 2 ; i ++ ; } for ( int j = 0 ; j < n - i ; j ++ ) cout << '0' ; for ( int j = i - 1 ; j >= 0 ; j -- ) cout << binaryNumber [ j ] ; } void generateGrayarr ( int n ) { int N = 1 << n ; for ( int i = 0 ; i < N ; i ++ ) { int x = i ^ ( i >> 1 ) ; decimalToBinaryNumber ( x , n ) ; cout << endl ; } } int main ( ) { int n = 3 ; generateGrayarr ( n ) ; return 0 ; }