Share my simple way of this problem^_^


  • 24
    B
    class Solution {
    public:
        vector<int> grayCode(int n) {
            int N(1 << n), tmp;
            vector<int> result;
            for(int i(0); i < N; i++)
            {
                tmp = i << 1;
                result.push_back((tmp^i) >> 1);
            }
            return result;
        }
    };
    

    As we known:

    Gi = Bi+1 xor Bi
    

    For example, trans binay '001' to gray code:

    tmp = 001 << 1
    

    then,

    bin 0 0 0 1
    tmp 0 0 1 0
    -xor------------
        0 0 1 1
    

    and the gray code is:

    0 0 1 1 >> 1 (ignore last bit) => 0 0 1

  • 1

    Don't understand how this works……:(


  • 6
    S

    My solution:

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

Log in to reply
 

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