LeetCode-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

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

class Solution {
public:
    inline int changeBit(int value,int i){
        unsigned int b=1;
    	i--;
        b=b<<i;
        if((b&value)>0){
            return value&(~b);
        }
        else{
            return value|b;
        }
        return value;
    }
    inline int differ(int a,int b){
        a=a^b;
        int i=1;
        for(;;){
            if(a&1){
                return i;
            }
            else{
                i++;
                a=a>>1;
            }
        }
    }
    vector<int> grayCode(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int>ret;

        if(n<0){
            return ret;
        }
        else if(n==0){
            ret.push_back(0);
            return ret;
        }
        int length=1;

		int b=n;
        for(;b>0;b--)length*=2;
        int* bits=new int[length];
        memset(bits,0,length*sizeof(int)/sizeof(char));
        
        ret.push_back(0);
        ret.push_back(1);
        int current=1;
        if(n==1){
            delete bits;
            return ret;
        }
        bits[0]=1;
       
        bits[current]++;
        bool forward=true;
        int i=1;
        for(;;){
			/*for(int j=0;j<ret.size();j++){
				cout<<ret[j]<<" ";
			}
			cout<<endl;*/
            if(forward){
                int v=changeBit(ret[current],i);
                current++;
                ret.push_back(v);
                if(bits[ret[current]]){
                    forward=false;
                }
                else{
                    forward=true;
					i=1;
                    if(current==length-1)
                    break;
                }
                bits[ret[current]]++;
            }
            else{
				bits[ret[current]]--;
                current--;
                i=differ(ret[current],ret[current+1]);
                ret.pop_back();
                if(i==n){
                    forward=false;
                }
                else {
                    forward=true;
                    i++;
                }
            }
        }
        delete bits;
        return ret;
    }
};

 

posted @ 2013-08-22 01:05  懒猫欣  阅读(242)  评论(0)    收藏  举报