6 lines C++ solution with bits operation


  • 0
    F
    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> result(1 << n, 0);
            for(int i = 1, mask; i < result.size(); ++i) {
                for(mask = 1; !(mask & i); mask <<= 1) ;
                result[i] = result[i - 1] ^ mask;
            }
            return result;
        }
    };
    

    the i-th bit of Gray Code flips once in every 2^i (power not xor) counting. How to find the flipping mask of (n-1)-th Gray Code to n-th? It's the rightest 1-bit of n.


Log in to reply
 

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