89. Gray Code [leetcode]

来源:互联网 发布:php好就业吗 编辑:程序博客网 时间:2024/05/23 14:01

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 - 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.

题目链接: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    0001     001    0012     011    0103     010    0114     110    1005     111    1016     101    1107     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位元格雷码

00011110
3位元格雷码
000001011010110111101100 
4位元格雷码
0000000100110010011001110101010011001101111111101010101110011000
4位元2进制原始码
0000000100100011010001010110011110001001101010111100110111101111



原创粉丝点击