Java for LeetCode 089 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=1 得到0 1
n=2 得到00 01 11 10(注意,11 和 10除了符号位外,和 00 01对称的)
n=3 得到000 001 011 010 110 111 101 100(后面四位除了符号位之外,和前四位对称)
n=4 依次类推
知道了格雷码的生成过程,那么JAVA实现如下:
static public List<Integer> grayCode(int n) { List<Integer> list=new ArrayList<Integer>(); for(int i=0;i<Math.pow(2, n);i++){ int result=0,num=i,temp=n; while(temp>1){ if(num>=Math.pow(2, temp-1)){ num=(int) (2*Math.pow(2, temp-1)-num-1); result+=Math.pow(2, temp-1); } temp--; } result+=num; list.add(result); } return list; }
同时,本题有一个非常简洁的写法,如下:
public List<Integer> grayCode(int n) { List<Integer> res = new ArrayList<Integer>(); for (int i = 0; i < (1<<n); ++i) res.add(i ^ (i>>1)); return res; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。