Generate n | 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
function decimalToBinaryNumber ( x , n ) { var binaryNumber = Array ( x ) ; var i = 0 ; while ( x > 0 ) { binaryNumber [ i ] = x % 2 ; x = parseInt ( x / 2 ) ; i ++ ; } for ( var j = 0 ; j < n - i ; j ++ ) document . write ( ' ' ) ; for ( var j = i - 1 ; j >= 0 ; j -- ) document . write ( binaryNumber [ j ] ) ; } function generateGrayarr ( n ) { var N = 1 << n ; for ( var i = 0 ; i < N ; i ++ ) { var x = i ^ ( i >> 1 ) ; decimalToBinaryNumber ( x , n ) ; document . write ( " " ) ; } } var n = 3 ; generateGrayarr ( n ) ;