您的位置:首页 > 其它

89. Gray Code [leetcode]

2017-08-08 12:15 357 查看
89. 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.

题目链接:https://leetcode.com/problems/gray-code/description/

解:

没想出来,根本不知道gray code是什么鬼。参看了讨论区及维基百科才明白怎么做。

先来看看为什么需要这个gray code:

(摘自维基百科 https://zh.wikipedia.org/wiki/%E6%A0%BC%E9%9B%B7%E7%A0%81

传统的二进制系统例如数字3的表示法为011,要切换为邻近的数字4,也就是100时,装置中的三个位元都得要转换,因此于未完全转换的过程时装置会经历短暂的,010,001,101,110,111等其中数种状态,也就是代表着2、1、5、6、7,因此此种数字编码方法于邻近数字转换时有比较大的误差可能范围。葛雷码的发明即是用来将误差之可能性缩减至最小,编码的方式定义为每个邻近数字都只相差一个位元,因此也称为最小差异码,可以使装置做数字步进时只更动最少的位元数以提高稳定性。 数字0~7的编码比较如下:

十进制 葛雷码 二进制
0     000    000
1     001    001
2     011    010
3     010    011
4     110    100
5     111    101
6     101    110
7     100    111


生成格雷码的方法:

方法一:镜面排列

n位元的格雷码可以从n-1位元的格雷码以上下镜射后加上新位元的方式快速的得到,如右图所示一般。



代码:

class Solution {
public:
vector<int> grayCode(int n) {
vector<int> res(1, 0);
for (int i = 0; i < n; i++) {
for (int j = res.size() - 1; j >=0; j--) {
res.push_back(res[j] + (1 << i));
}
}
return res;
}

};

方法二:直接排列

以二进制为0值的格雷码为第零项,第一项改变最右边的位元,第二项改变右起第一个为1的位元的左边位元,第三、四项方法同第一、二项,如此反复,即可排列出n个位元的格雷码。

方法三:二进制数转格雷码

(假设以二进制为0的值做为格雷码的0)
G:格雷码 B:二进制码
G(N) = (B(n)/2) XOR B(n)

2位元格雷码
00
01
11
10

3位元格雷码
000
001
011
010
110
111
101
100

4位元格雷码
0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000

4位元2进制原始码
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 格雷码