Friday, April 10, 2015

89 Gray Code

The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
00 - 0
01 - 1
11 - 3
10 - 2
class Solution {
public:
    vector<int> grayCode(int n) {
        if (n==0)
        {
            vector<int> res = vector<int>(1,0);
            return res;
        }
        vector<int> res = grayCode(n-1);
        int i = res.size()-1;
        for (;i>=0;i--)
        {
            int temp = res[i];
            temp = temp | (1<<(n-1));
            res.push_back(temp);
        }
        return res;
    }
};
class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> res = vector<int>(1,0);
        for (int i=1;i<=n;i++)
        {
            for (int j = res.size()-1;j>=0;j--)
            {
                int temp = res[j];
                temp = temp|(1<<(i-1));
                res.push_back(temp);
            }
        }
        return res;
    }
};

No comments:

Post a Comment