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
Gray Code, 每次看每次都不記得。寫下來讓自己好溫習。
Gray Code 0 = 0, 下一項是toggle最右邊的bit(LSB), 再下一項是toggle最右邊值為 “1” bit的左邊一個bit。然后重復
如: 3bit
Gray Code: 000, 001, 011, 010, 110, 111, 101, 100, 最右邊值為 “1” 的bit在最左邊了,結束。
Binary : 000, 001, 010, 011, 100, 101, 110, 111
再者就是Binary Code 轉換為Gray Code了。
如:
Binary Code :1011 要轉換成Gray Code
1011 = 1(照寫第一位), 1(第一位與第二位異或 1^0 = 1), 1(第二位異或第三位, 0^1=1), 0 (1^1 =0) = 1110
其實就等於 (1011 >> 1) ^ 1011 = 1110
有了上面的等式寫code就簡單了
class Solution { public: vector<int> grayCode(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function int size = 1<<n; vector<int> grayCodes; grayCodes.resize(size); for (int i = 0; i < size; i++){ int gCode = i ^ i>>1; grayCodes[i] = gCode; } return grayCodes; } };
EOF
