标签:style blog io color ar for sp div on
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.
思路:格雷码问题。
二进制转格雷码:二进制最高位作为格雷码最高位。格雷码其他各位是相应的二进制位其较高临位的异或。
即,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)
标签:style blog io color ar for sp div on
原文地址:http://www.cnblogs.com/vincently/p/4054977.html