Generate n | Java program to generate n - bit Gray codes ; This function generates all n bit Gray codes and prints the generated codes ; Base case ; Recursive case ; Append 0 to the first half ; Append 1 to the second half ; Function to generate the Gray code of N bits ; print contents of arr ; Driver Code
using System ; using System . Collections . Generic ; class GFG { static List < String > generateGray ( int n ) { if ( n <= 0 ) { List < String > temp = new List < String > ( ) ; temp . Add ( "0" ) ; return temp ; } if ( n == 1 ) { List < String > temp = new List < String > ( ) ; temp . Add ( "0" ) ; temp . Add ( "1" ) ; return temp ; } List < String > recAns = generateGray ( n - 1 ) ; List < String > mainAns = new List < String > ( ) ; for ( int i = 0 ; i < recAns . Count ; i ++ ) { String s = recAns [ i ] ; mainAns . Add ( "0" + s ) ; } for ( int i = recAns . Count - 1 ; i >= 0 ; i -- ) { String s = recAns [ i ] ; mainAns . Add ( "1" + s ) ; } return mainAns ; } static void generateGrayarr ( int n ) { List < String > arr = new List < String > ( ) ; arr = generateGray ( n ) ; for ( int i = 0 ; i < arr . Count ; i ++ ) { Console . WriteLine ( arr [ i ] ) ; } } public static void Main ( String [ ] args ) { generateGrayarr ( 3 ) ; } }