题目描述
java实现
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> result = new LinkedList<>();
//1<<2 = 100(4)
for (int i = 0; i < 1<<n; i++) {
result.add(i ^ i >> 1);
// 00(0) ^ 00 =00
// 01(1) ^ 00 =01
// 10(2) ^ 01 =11
// 11(3) ^ 01 =10
}
return result;
}
}
/*
<<:左移运算符:相当于乘以2,二进制码整体左移,左边超出的部分舍弃,右边补零
>>:右移运算符:相当于除以2,二进制码整体右移,左边的用符号位的数组补充(整数符号位为0,负数符号位为1),右边超出的部分舍弃
>>>:无符号右移:不管正负标志位为0还是1,将该数的二进制码整体右移,左边部分总是以0填充,右边部分舍弃。
异或运算(不同为1,相同为0)
1、交换律
2、结合律(即(a^b)^c == a^(b^c))
3、对于任何数x,都有x^x=0,x^0=x
4、自反性 A XOR B XOR B = A xor 0 = A
*/
参考
https://leetcode.com/problems/gray-code/discuss/29881/An-accepted-three-line-solution-in-JAVA