题目链接:https://leetcode.com/problems/gray-code/submissions/
代码
class Solution:
def grayCode(self, n: int) -> List[int]:
return [ i^i>>1 for i in range(1<<n)]
思路详解
格雷编码:在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码(Gray Code),另外由于最大数与最小数之间也仅一位数不同,即“首尾相连”,因此又称循环码或反射码。
思路:
n位,可以编码
2
n
2^n
2n个值
- 1 << n :1右移n位,表示 2 n 2^n 2n
- i >>1 : i 左移一位,相当于除2
- i ^ i >>1:结局如是,至于为什么——找规律