Accepted solution, 4ms, 3 line, c++ code.


  • 2
    S
    vector<int> grayCode(int n) {
        vector<int> ans;
        for(int i=0; i<(1<<n); ++i)  ans.push_back((i>>1)^i);
        return ans;
    }
    

    Enjoy.


  • 0
    T

    First of all, wow! Second, can you please explain a little? I know one bit difference means that two consecutive elements' XOR must be a power of two, but how did you reverse this fact to shifting right?


Log in to reply
 

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