Very Short Java Solution without playing with bit manipulation


  • 0
    public class Solution {
        public List<Integer> grayCode(int n) {
            List<Integer> res = new ArrayList<Integer>();
            res.add(0);
            if(n <= 0) return res;
            res.add(1);
            for(int i = 1; i <= n - 1; i++){
                for(int j = res.size() - 1; j >= 0; j--){
                    res.add((int)Math.pow(2, i) + res.get(j));
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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