首页 > 代码库 > [LeetCode] Gray Code
[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 - 001 - 111 - 310 - 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.
思路:格雷码问题。
二进制转格雷码:二进制最高位作为格雷码最高位。格雷码其他各位是相应的二进制位其较高临位的异或。
即,gray_code(t) = binary_code(t) //t是最高位
gray_code(i) = binary_code(i) ^binary_code(i + 1) // 0<= i < t;
1 class Solution { 2 public: 3 vector<int> grayCode(int n) { 4 vector<int> res; 5 const int size = 1 << n; 6 for (int i = 0; i < size; ++i) { 7 res.push_back((i>>1) ^ i); 8 } 9 10 return res;11 12 }13 };
拓展:
- 格雷码转二进制:二进制最高位是为格雷码的最高位。二进制次高位是二进制高位与格雷码次高位异或,其他各位与次高位求法相同
binary_code(t) = gray_code(t) //t是最高位
binary_code(i) = gray_code(i) ^ binary_code(i +1) // 0 <=i < t
2. 整数n的格雷码为: n^(n/2)
[LeetCode] Gray Code