letcode Gray code

Gray Code
描述
e 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
01
11
10
-
-
-
-
0
1
3
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) 的定义请参考 wikipedia http://en.wikipedia.org/wiki/Gray_code。 
自然二进制码转换为格雷码:g 0 = b 0 , g i = b i ⊕ b i−1
保留自然二进制码的最高位作为格雷码的最高位,格雷码次高位为二进制码的高位与次高位异
或,其余各位与次高位的求法类似。例如,将自然二进制码 1001,转换为格雷码的过程是:保留最
高位;然后将第 1 位的 1 和第 2 位的 0 异或,得到 1,作为格雷码的第 2 位;将第 2 位的 0 和第 3 位
的 0 异或,得到 0,作为格雷码的第 3 位;将第 3 位的 0 和第 4 位的 1 异或,得到 1,作为格雷码的
第 4 位,最终,格雷码为 1101。
格雷码转换为自然二进制码:b 0 = g 0 , b i = g i ⊕ b i−1
保留格雷码的最高位作为自然二进制码的最高位,次高位为自然二进制高位与格雷码次高位异
或,其余各位与次高位的求法类似。例如,将格雷码 1000 转换为自然二进制码的过程是:保留最高
位 1,作为自然二进制码的最高位;然后将自然二进制码的第 1 位 1 和格雷码的第 2 位 0 异或,得到
1,作为自然二进制码的第 2 位;将自然二进制码的第 2 位 1 和格雷码的第 3 位 0 异或,得到 1,作
为自然二进制码的第 3 位;将自然二进制码的第 3 位 1 和格雷码的第 4 位 0 异或,得到 1,作为自然
二进制码的第 4 位,最终,自然二进制码为 1111。
格雷码有数学公式,整数 n 的格雷码是 n ⊕ (n/2)。
这题要求生成 n 比特的所有格雷码。

最简单的方法,利用数学公式,对从 0 ∼ 2 n − 1 的所有整数,转化为格雷码。

代码:

#include <iostream>
#include <vector>

using namespace std;

class Gray_code
{
public:
	vector<int> Gray(int n)
	{
		vector<int> result;
		const size_t size= 1<<n;
		result.reserve(n);
		for (int i = 0; i < size; ++i)
		{
			result.push_back(binary_to_gray(i));
		}

		return result;
	}
private:
	static unsigned int binary_to_gray(unsigned int n)
	{
		return n^(n>>1);
	}
	static unsigned int gray_to_binary(unsigned int g)
	{
		for(unsigned int mask= g>>1;mask!=0;mask>>1)
			g=g^mask;
		return g;
	}

};


void Print2(unsigned int data)
{ //此处不作数字检查
    int i ;
    int count=0;
    for(i=0;i<4;i++)
    {
        if((data&0x8)==0x8)
        { 					
            cout<<1;    
        }
        else
        {
            cout<<0;
        }
        data=data<<1;
    } 
}
int main(int argc, char const *argv[])
{
	Gray_code gray;
	vector<int> hello;
	hello.reserve(50);
	hello=gray.Gray(4);
	for (int i = 0; i < (hello.size()); ++i)
	{
		int temp=hello[i];
		Print2(temp);
		cout<<"  "<<temp<<endl;
	}
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值