My java solution


  • 0
    V

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    public class GrayCode {

    public static void main(String args[]){
        GrayCode grayCode=new GrayCode();
        grayCode.grayCode(0);
    }
    public List<Integer> grayCode(int n) {
        if(n<0){
            return null;
        }
        List<Integer> numbers = new ArrayList<Integer>();
        numbers.add(0);
       
        if(n==0){
            return numbers;
        }
       
        numbers.add(1);
        for(int bit=1;bit<n;bit++){
            List<Integer> tempList=new ArrayList<Integer>();
            tempList.addAll(numbers);
            Collections.reverse(numbers);
            int flagNum=1<<bit;
            for(int i=0;i<numbers.size();i++){
                int numberI = numbers.get(i);
                numbers.remove(i);
                numbers.add(i, numberI | flagNum);
            }
            tempList.addAll(numbers);
            numbers=tempList;
        }
       
        for(int i=0;i<numbers.size();i++){
            System.out.println("Number at position "+i+ " is "+numbers.get(i));
        }
       
        System.out.println("Size of list is "+numbers.size());
        return numbers;
    }
    

    }


Log in to reply
 

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