C++ Basically 1 liner simple bit manipulation


  • -1
    A

    Well, the generation is actually done in 1 line. Can't be even simpler.
    Unlike others whose algorithms came from google or wiki, I devised this method all by myself, without any reference.

    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> v;
            for (uint m = 0, i = 1; i <= (1<<n); i++) {
                v.push_back(m);
                m ^= i & -i;
            }
            return v;
        }
    };
    

Log in to reply
 

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