leetcode 之 Gray Code 解题思路

题目如下:

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位的二进制码转变成相应的格雷码。下面给出二进制码和格雷码的对应,举例n=3,从中找到转化的规律

十进制       二进制        格雷码

0                   000             000

1                   001             001

2                   010             011

3                   011             010

4                   100             110

5                   101             111

6                   110             101

7                   111             100

二进制转格雷码的规律为:先在二进制最左边添加0,举例 010 -> 0010, 再前一位与后一位异或,得到后一位的格雷码值,即:0^0=0; 0^1=1; 1^0=1; 因此得到格雷码011。

该过程其实就相当于将二进制右移一位,再与自身异或,举例: 010 右移一位得到 001; 001^010=011。

所以解题思路就是:

(1)根据n得到所有10进制的个数  1<<n

(2)对每个数,(i >>1)^i 即为i对应的格雷码

代码如下:

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

点赞