089 Gray Code 格雷编码

格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
给定一个代表编码总位数的非负整数 n,打印格雷码序列。格雷码序列必须以0开头。
例如, 给定 n = 2, 返回 [0,1,3,2]。其格雷编码是:
00 - 0
01 - 1
11 - 3
10 - 2
注意:
对于给定的 n,其格雷编码的顺序并不唯一。
例如 [0,2,3,1] 也是一个有效的格雷编码顺序。
目前,系统只可以根据一个格雷编码序列实例进行判断。请您谅解。
详见:https://leetcode.com/problems/gray-code/description/

Java实现:

class Solution {
    public List<Integer> grayCode(int n) {
        int num=1<<n;
        List<Integer> res=new ArrayList<Integer>();
        int i=0;
        while(i<num){
            res.add(i^(i>>1));
            ++i;
        }
        return res;
    }
}

 详见:https://www.cnblogs.com/grandyang/p/4315649.html

https://www.nowcoder.com/questionTerminal/50959b5325c94079a391538c04267e15?pos=4&orderByHotValue=1

原文地址:https://www.cnblogs.com/xidian2014/p/8716499.html