LeetCode - gray-code

本文介绍了一种基于二进制转换的格雷码生成方法,通过简单的位操作实现了格雷码序列的快速生成。适用于计算机科学领域,特别是数据通信和数字逻辑设计中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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来求二进制转化为格雷码的所有结果

 

解题思路:

刚开始还没看懂,后来去维基百科搜了下格雷码 ,找到了二进制转格雷码的公式

(假设以二进制为0的值做为格雷码的0)
G:格雷码 B:二进制码 n:正在计算的位 
根据格雷码的定义可得:
G(n) = B(n+1) XOR B(n) 
即 
G(n) = B(n+1) + B(n) 
自低位至高位运算即可,无需考虑进位,

2位元格雷码
00
01
11
10
3位元格雷码
000
001
011
010
110
111
101
100 
4位元格雷码
0000
0001
0011
0010
0110
0111
0101
0100
1100
1101
1111
1110
1010
1011
1001
1000
4位元2进制原始码
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111

 

用Java代码表示:

/*
	 * 二进制转格雷码
	 * @param num 多少位
	 * @return 返回当前位数的格雷码
	 */
	public static int binaryToGray (int num) {
		return (num>>1)^num;
	}

 

所以这里的答案就直接在循序里套用这个函数,然后集合添加就行。

public  ArrayList<Integer> grayCode(int n) {
		
        ArrayList<Integer> list = new ArrayList<Integer>();
        if(n < 0 ) {
        	return list;
        }
        for(int i = 0;i < 1<<n;i++) {
        	list.add((i>>1)^i);
        }
        
        return list;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值