A solution based on the gray code generation formula


  • 1
    L

    The gray code can be generated using formula from wikipedia. Specifically, the nth gray code is n ^ (n >> 1).
    The code is as below. This line of code is added to pass OJ: if(n == 0) result.add(0);

    public class Solution {
        public List<Integer> grayCode(int n) {
            List<Integer> result = new ArrayList<Integer>();
            if(n <= 0){
                if(n == 0) result.add(0);
                return result;
            }
            for(long i = 0; i < (long)Math.pow(2, n); i++){
                result.add((int)(i ^ (i >> 1)));
            }
            return result;
        }
    }

Log in to reply
 

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