您的位置:首页 > 其它

[LeetCode]—Gray Code 计算格雷码

2014-06-19 11:57 531 查看


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
Code)。当初是为了通信,现在则常用于模拟-数字转换和位置-数字转换中。

格雷码有多种编码形式。若不作特别说明,格雷码就是指典型格雷码,它可从自然二进制码转换而来。

转换方法: 二进制码→格雷码(编码)

方法一:递归生成码表

这种方法基于格雷码是反射码的事实,利用递归的如下规则来构造:

1位格雷码有两个码字

(n+1)位格雷码中的前2n个码字等于n位格雷码的码字,按顺序书写,加前缀0

(n+1)位格雷码中的后2n个码字等于n位格雷码的码字,按逆序书写(将前一个结果反转一下),加前缀1



方法二:异或转换

此方法从对应的n位二进制码字中直接得到n位格雷码码字,步骤如下:

对n位二进制的码字,从右到左,以0到n-1编号

如果二进制码字的第i位和i+1位相同,则对应的格雷码的第i位为0,否则为1(当i+1=n时,二进制码字的第n位被认为是0,即第n-1位不变)

例如:二进制码0101,为4位数,所以其所转为之格雷码也必为4位数,因此可取转成之二进位码第五位为0,即0 b3 b2 b1 b0。

0 xor 0=0,所以g3=0

0 xor 1=1,所以g2=1

1 xor 0=1,所以g1=1

0 xor 1=1,所以g0=1
因此所转换为之格雷码为0111



格雷码→二进制码(解码):

从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变)。依次异或,直到最低位。依次异或转换后的值(二进制数)就是格雷码转换后二进制码的值。

举例:
如果采集器器采到了格雷码:1010
就要将它变为自然二进制:
0 与第四位 1 进行异或结果为 1
上面结果1与第三位0异或结果为 1
上面结果1与第二位1异或结果为 0
上面结果0与第一位0异或结果为 0
因此最终结果为:1100 这就是二进制码即十进制 12

采用第一种递归的方法解题:

<span style="font-family:Arial;font-size:12px;">class Solution{</span>
public:
vector<int> grayCode(int n){
vector<int> result;
compute_grayCode(n,result);
return result;

}

void compute_grayCode(int n,vector<int> &temp)
{
unsigned int highest= 1<<n-1;
if(n==0){
temp.push_back(0);
return;
}
if(n==1){
temp.push_back(0);
temp.push_back(1);
return;
}
compute_grayCode(n-1,temp);
vector<int> r_temp(temp);
reverse(r_temp.begin(),r_temp.end());
for(int  i=0;i<r_temp.size();++i)
temp.push_back(highest | r_temp[i]);
}

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