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;
}