4 line AC JAVA solution


  • 0
    K

    public class Solution {

    public List<Integer> grayCode(int n) {
        List<Integer> ret = new LinkedList<Integer>();
        for (int i = 0; i < Math.pow(2,n); i++)
        	ret.add(((i << 1) ^ i) >> 1);
        return ret;
    }
    

    }

    a gray code sequence will follow the equation:

    [0, ..... (((i-1) << 1)^(i-1)) >> 1, ((i << 1) ^ i) >>1, (((i+1) << 1)^(i+1)) >> 1.......]


  • 0
    I

    you could also have done ret.add((i>>1)^i);


Log in to reply
 

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