simple solution very easy using one loop 3 lines.. simple trick easy to understand


  • 0
    P

    For every number in the total no of bits i^(i/2) gives the gray code in at i. As long as we increase i by one at a time , we will get the sequence. But to iterate i , take the power of input by 2.

    eg. 3 is input means you have i ranging from 0 to 7.

    eg.5 .. 101 ^(5/2) = 101 ^ 010 = 111 which is 7

        public List<Integer> grayCode(int n) {
             
             LinkedList<Integer> list=new LinkedList<Integer>();
            
            //power to get total no of bits 
            int npower =(int)Math.pow(2,n);
            
            for(int i=0;i<npower;i++){
            	int greyCode = i ^ (i / 2); // this gives gray code at i
    			list.add(greyCode);
                
            }
            
            return list;
            
            
        }
    }```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.