您的位置:首页 > 其它

LeetCode|Gray Code

2016-04-30 19:45 381 查看

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.

思路:

(i+1)位的标准格雷码可由i位的格雷码递推出。参考wiki

—— 一位格雷码

000

001

—— 二位格雷码

011

010

—— 三位格雷码

110

111

101

100

所以可以看出,i-1位格雷码的最高位补0,再加上逆序的i-1位格雷码最高位补1,就可以得到i位格雷码。

class Solution {
public:
vector<int> grayCode(int n) {
if(n == 0) return vector<int>(1, 0);
vector<int> res;
res.resize(pow(2, n) );
res[0] = 0, res[1] = 1;
unsigned int firstBitPos = 1;
unsigned int len = 2;

for(int i = 1; i < n; i++){
firstBitPos <<= 1;
len <<= 1;
for(int j = 0, k = len-1; j < k; j++, k--){
res[k] = res[j]|firstBitPos;
}
}
return res;
}
};


自然二进制数转换到格雷码

设有 N 位二进制数 B(i),其中 0 ≤ i ≤ N - 1;

二进制数与格雷码的转换公式如下:

  G(i) = B(i+1) XOR B(i) ; 0 <= i < N - 1

  G(i) = B(i) ; i = N - 1

格雷码转换到自然二进制数

设有 N 位格雷码 G(i),把它转换成自然二进制数的算法如下。

自然二进制码的最高位等于雷码的最高位;

自然二进制码的次高位为最高位自然二进制码与次高位格雷码相异或;

自然二进制码的其余各位与次高位自然二进制码的求法相类似。

转换公式如下:

  B(i) = G(i) ; i = N - 1

  B(i) = B(i+1) XOR G(i) ; 0 <= i < N - 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: