[java/1ms] neat code with explanation.


  • 0

    0| 1 | 3 2 | 6 7 5 4 | ....
    prev 0 2^0 2^1 2^2

    public List<Integer> grayCode(int n) {
            List<Integer> ret = new ArrayList<>();
            ret.add(0);
            for (int i = 1, shift = 1; i <= n; i++) {
                // mirror from previous 2 ^ (i-1) 
                for (int j = shift-1; j >= 0; j--) {
                    // ret.get(j) ^ shift is more efficient here that +
                    ret.add((ret.get(j) ^ shift));
                }
                shift <<= 1;
            }
            
            return ret;
        }
    

Log in to reply
 

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