My C++ Code (6ms)

  • 0

    The basic idea is the second half of the gray code list is a mirrow copy of the first half plus the offset 2^(n-1).
    By the way, Gray code is very useful in HW design (e.g. finite state machine,...)

    class Solution {
            vector<int> grayCode(int n) {
                vector<int> result;
                int i, pow_2, offset;
                    for(pow_2 =0;pow_2<n;pow_2++)
                        offset = 1<<pow_2; // offset for the second half, just set the (pow_2)-th bit to 1
                        { // mirrow copy the first half, and plus the offset
                            result.push_back(result[result.size()-1 - 2*i] + offset );
                return result;

Log in to reply

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