加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

gray-code

发布时间:2020-12-14 05:11:51 所属栏目:大数据 来源:网络整理
导读:/** * * @author gentleKay * 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

/**
*
* @author gentleKay
* 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,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开头。
* 例如,给定n=2,返回[0,2]。其灰色代码序列为:
* 00 - 0
01 - 1
11 - 3
10 - 2
* 注:
* 对于给定的n,灰色代码序列不是唯一定义的。
* 例如,根据上述定义,[0,1]也是有效的灰色代码序列。
* 目前,法官能够根据一个灰色编码序列的实例进行判断。很抱歉。
*/

这道题如果你知道格雷码和移位运算符,那解决起来很简单。

格雷码:https://baike.baidu.com/item/%E6%A0%BC%E9%9B%B7%E7%A0%81

移位运算符:https://www.cnblogs.com/winsker/p/6728672.html

import java.util.ArrayList;

/**
 * 
 * @author gentleKay
 * 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,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,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开头。
 * 例如,给定n=2,返回[0,2]。其灰色代码序列为:
 *		00 - 0
		01 - 1
		11 - 3
		10 - 2
 * 注:
 * 对于给定的n,灰色代码序列不是唯一定义的。
 * 例如,根据上述定义,[0,1]也是有效的灰色代码序列。
 * 目前,法官能够根据一个灰色编码序列的实例进行判断。很抱歉。
 */

public class Main23 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(Main23.grayCode(2));
	}
	
	public static ArrayList<Integer> grayCode(int n) {
        ArrayList<Integer> array = new ArrayList<>();
        int num = 1 << n; 
        for (int i=0;i<num ;i++) {
        	array.add(i >> 1^i);  //格雷码,十进制转二进制    和  >> 运算优先级高于 ^
        }
        return array;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读