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 ; ' arr ' will store all generated codes ; start with one - bit pattern ; Every iteration of this loop generates 2 * i codes from previously generated i codes . ; Enter the prviously generated codes again in arr [ ] in reverse order . Nor arr [ ] has double number of codes . ; append 0 to the first half ; append 1 to the second half ; print contents of arr [ ] ; Driver program to test above function
import java . util . * ; class GfG { static void generateGrayarr ( int n ) { if ( n <= 0 ) return ; ArrayList < String > arr = new ArrayList < String > ( ) ; arr . add ( "0" ) ; arr . add ( "1" ) ; int i , j ; for ( i = 2 ; i < ( 1 << n ) ; i = i << 1 ) { for ( j = i - 1 ; j >= 0 ; j -- ) arr . add ( arr . get ( j ) ) ; for ( j = 0 ; j < i ; j ++ ) arr . set ( j , "0" + arr . get ( j ) ) ; for ( j = i ; j < 2 * i ; j ++ ) arr . set ( j , "1" + arr . get ( j ) ) ; } for ( i = 0 ; i < arr . size ( ) ; i ++ ) System . out . println ( arr . get ( i ) ) ; } public static void main ( String [ ] args ) { generateGrayarr ( 3 ) ; } }