Instead of changing the highest bit, I appended 0 and 1


  • 0
    D

    Is this correct? Instead of changing the highest bit, I appended 0 and 1 to previous gray code.

    Thanks

    vector<int> grayCode(int n) {
        vector<int> r;
        r.push_back(0);
        if (n==0)
        return r;
        
    
        r.push_back(1);
        
        if (n==1)
        return r;
        
        for (int i=1;i<n;i++)
        {
            vector<int> tmp;
            int k = r.size();
            for (int j=0;j<k; j++)
            {
                tmp.push_back(r[j]<<1);
            }
            for (int j=k-1;j>=0; j--)
            {
                tmp.push_back((r[j]<<1)+1);
            }      
            r=tmp;
        }
        return r;
    }

Log in to reply
 

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