Direct calculation of each entry in case you're asked to generate a specific entry only


  • 0
    H
        vector<int> grayCode(int n) {
            int total = 1 << n;
            vector<int> result(total, 0);
            
            for (int i = 0; i < result.size(); i++){
                int thres = total >> 1;    
                while (thres){
                    result[i] *= 2;
                    result[i] += ((i / thres) % 4 == 2 || (i / thres) % 4 == 1) ? 1 : 0;
                    thres = thres >> 1;
                }
            }
            
            return result;
        }
    

Log in to reply
 

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