Leetcode 89. Gray Code 格雷码 解题报告

1 解题思想

这个gray code,是一个编码,相邻的数所对应的编码只有1位不相同

这题嘛,原理我也不太懂。。大家可以看下这个链接

http://www.matrix67.com/blog/archives/266
或者背下来好了,手动滑稽~

2 原题

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. S
orry about that.

3 AC 解

public class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> list =new ArrayList<Integer>();
        for(int i=0;i<Math.pow(2,n);i++){
            list.add(i ^ (i >> 1));
        }
        return list;
    }
}

你可能感兴趣的:(LeetCode,编码,格雷码,gray-code,gray码)