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
一种二进制编码方式,相邻编码只有一位不同。格雷码的产生方式有以下两种。
第一,递归产生。这种方法基于格雷码是反射码的事实,利用递归的如下规则来构造:
1、1位格雷码有两个码字
2、(n+1)位格雷码中的前2n个码字等于n位格雷码的码字,按顺序书写,加前缀0
3、(n+1)位格雷码中的后2n个码字等于n位格雷码的码字,按逆序书写,加前缀1
第二、异或转换。此方法从对应的n位二进制码字中直接得到n位格雷码码字,步骤如下:
1、对n位二进制的码字,从右到左,以0到n-1编号
2、如果二进制码字的第i位和i+1位相同,则对应的格雷码的第i位为0,否则为1(当i+1=n时,二进制码字的第n位被认为是0,即第n-1位不变)
public List<Integer> grayCode(int n) {
List<Integer> l = new ArrayList<Integer>();
l.add(0);
for(int i = 1; i < (int)(Math.pow(2,n));i++){
l.add((i/2)^i);
}
return l;
}