Gray Code

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



本题以格雷码为引子,有两种解法,一种是寻找格雷码变化规律,然后模拟变化过程,得出结果;另一种是用异或。

方法一:模拟

例如当n=2时,格雷码如下:

00
01
11
10
 
当n=3时,格雷码
000
001
011
010

110
111
101
100
由以上可以看到规律:n的格雷码由n-1格雷码推导出来。在n-1格雷码左边加个0,以及在n-1的格雷码最左边加个1,然后把n-1个格雷码逆序。时间复杂度O(n^2)
根据以上规律写出代码
vector<int> grayCode(int n) 
{
	vector<int> res;

	res.push_back(0); 
	//从0--n逐个添加到res中
	for (int i = 0; i < n; i++)
	{
		//左移一位,相当于h = 2^i,也就是格雷码的	1*******,因为0******已经保存在res中了
		int h = 1 << i;
		int len = res.size();
		//逆序添加,根据以往保存在res中的数据再加上1******就是要添加的
		for (int j = len-1; j >= 0; j--)
		{
			res.push_back(h + res[j]);
		}
	}

	return res;
}

方法二、

运用格雷码和二进制的转换,参考


时间效率高。
### Gray Code Counter Implementation in Digital Circuit Design Gray code 是一种二进制编方式,其特点是相邻两个数值之间仅有一位发生变化。这种特性在数字电路设计中特别有用,尤其是在减少开关噪声和避免状态跳跃方面。Gray code counter(格雷计数器)是一种使用 Gray code进行计数的数字电路,通常用于编器、解器和状态机设计等领域。 #### 格雷计数器的基本结构 一个典型的 Gray code counter 实现包括以下几个主要部分: 1. **二进制计数器**:首先使用一个标准的二进制加法计数器(如 4 位或 8 位的同步计数器)来生成递增的二进制值。 2. **二进制到 Gray 转换器**:将二进制计数器输出的值转换为相应的 Gray 。转换公式为: ``` G[i] = B[i] XOR B[i+1] ``` 其中 `G[i]` 是 Gray 的第 i 位,`B[i]` 是二进制数的第 i 位。 3. **Gray 到二进制转换器(可选)**:如果需要将 Gray 转换回二进制形式,可以使用逆向转换公式: ``` B[i] = G[i] XOR B[i+1] ``` #### 数字电路实现示例 以下是一个简单的 4 位 Gray code counter 的 Verilog 实现示例: ```verilog module gray_code_counter( input clk, input reset, output reg [3:0] binary_count, output [3:0] gray_code ); always @(posedge clk or posedge reset) begin if (reset) binary_count <= 4'b0; else binary_count <= binary_count + 1; end assign gray_code = binary_count ^ (binary_count >> 1); endmodule ``` 在上述代中,`binary_count` 是一个标准的二进制计数器,`gray_code` 通过将 `binary_count` 与其右移一位后的值进行异或操作来生成 Gray 输出。 #### 应用场景 Gray code counter 在数字电路设计中广泛应用于以下领域: - **编器与解器**:用于减少在状态转换过程中可能出现的错误。 - **旋转编器**:在机械系统中,用于检测旋转位置,避免因多比特同时变化而导致的误读。 - **FPGA 和 ASIC 设计**:在需要减少信号切换噪声的场合,Gray code 被用来优化电路性能。 #### 设计优化 在实际设计中,Gray code counter 可以通过以下方式进行优化: - **减少逻辑门数量**:通过优化转换逻辑,减少所需的逻辑门数量,从而降低功耗和延迟。 - **同步与异步设计**:根据应用需求选择同步或异步计数器结构,以满足时序要求。 Gray code counter 的实现不仅限于硬件描述语言(如 Verilog 或 VHDL),也可以通过逻辑门电路直接构建,适用于各种数字系统设计场景[^1]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值