[LeetCode]Gray Code

本文介绍了一种生成灰码(Gray Code)的算法实现方法。灰码是一种特殊的二进制数序列,相邻两个数只有一位不同。文章提供了两种不同的实现思路及其对应的Java代码:递归方法和基于位运算的方法。

摘要生成于 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.

给出一种格雷码的实现。

解题思路

什么是Gray Code?
      在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码(Gray Code),另外由于最大数与最小数之间也仅一位数不同,即“首尾相连”,因此又称循环码或反射码。在数字系统中,常要求代码按一定顺序变化。例如,按自然数递增计数,若采用8421码,则数0111变到1000时四位均要变化,而在实际电路中,4位的变化不可能绝对同时发生,则计数中可能出现短暂的其它代码(1100、1111等)。

怎样解题?
     乍一看题目貌似很麻烦。每一次将二进制码中的一位和上一个数相同的一位改变。怎样实现呢?

思路1
    通过观察我们发现一种实现格雷码的方法:
   
grayCode(n) = grayCode(n-1) + (grayCode(n)+2^(n-1))逆转;

思路2:
    这个是参考网上的帖子才知道的。
    二进制码->格雷码(编码):从最右边一位起,依次将每一位与左边一位异或(XOR),作为对应格雷码该位的值,最左边一位不变(相当于左边是0);
    格雷码->二进制码(解码):从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值(最左边一位依然不变)。
    这种方法更具有普适性,而且代码精炼。

代码

思路1代码:
public static ArrayList<Integer> grayCode(int n) {
		ArrayList<Integer> list  = new ArrayList<Integer>(n);
		
		if(n==0){
			list.add(0);
			return list;
		}
		if(n==1){
			list.add(0);
			list.add(1);
			return list;
		}
		
		ArrayList<Integer> childList = grayCode(n-1);
		int pow = (int) Math.pow(2, n-1);
		list.addAll(childList);
		for(int i = childList.size() - 1;i >= 0;i--){
			list.add(childList.get(i) + pow);
		}
		return list;
	}

思路2代码:
public static ArrayList<Integer> grayCode(int n) {
		ArrayList<Integer> list  = new ArrayList<Integer>(n);
		
		if(n==0){
			list.add(0);
			return list;
		}
		int nSize = 1 << n;  
        for (int i = 0; i < nSize; ++i)  
        {  
            list.add((i>>1)^i);  
        }  
		return list;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值