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. 本文地址
二进制转格雷码:gray = (binary) xor (binary >> 1)
代码如下:
1 class Solution { 2 public: 3 vector<int> grayCode(int n) { 4 //注意n = 0时,输出{0}而不是空数组 5 int num = 1<<n; 6 vector<int> res; 7 res.reserve(num); 8 for(int i = 0; i < num; i++) 9 res.push_back(i^(i>>1)); 10 return res; 11 } 12 };
这篇文章有一个对格雷码很有意思的解释
顺便科普一下解码(格雷码 转 二进制码)方法(摘自百度百科):
举例:
如果采集器器采到了格雷码:1010
就要将它变为自然二进制:
0 与第四位 1 进行异或结果为 1
上面结果1与第三位0异或结果为 1
上面结果1与第二位1异或结果为 0
上面结果0与第一位0异或结果为 0
因此最终结果为:1100 这就是二进制码即十进制 12
当然人看时只需对照表1一下子就知道是12
|
【版权声明】转载请注明出处:http://www.cnblogs.com/TenosDoIt/p/3451938.html