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.
二進制碼->格雷碼(編碼):從最右邊一位起,依次將每一位與左邊一位異或(XOR),作爲對應格雷碼該位的值,最左邊一位不變(相當於左邊是0);
格雷碼->二進制碼(解碼):從左邊第二位起,將每位與左邊一位解碼後的值異或,作爲該位解碼後的值(最左邊一位依然不變)。
Gray Code 0 = 0, 下一項是toggle最右邊的bit(LSB), 再下一項是toggle最右邊值爲 “1” bit的左邊一個bit,然後重複。直到最右邊值爲 “1” 的bit在最左邊了,結束。
- class Solution {
- public:
- vector<int> grayCode(int n) {
- // Start typing your C/C++ solution below
- // DO NOT write int main() function
- vector<int> result;
- int nSize = 1 << n;
- for (int i = 0; i < nSize; ++i)
- {
- result.push_back((i>>1)^i);
- }
- return result;
- }
- };
轉載於:https://www.cnblogs.com/ericsun/p/3320429.html