[letecode java] Gray Code

来源:互联网 发布:飞鸽翻墙软件下载 编辑:程序博客网 时间:2024/06/05 18:15

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 - 001 - 111 - 310 - 2

本题让我们求输入n时的格雷码。要是知道格雷码就很简单了,就一个数组更新的问题。如果不知道格雷码,通过观察,我们依然能找到规律。观察n=2和n=1时的格雷码,可以得到以下规律。n=k时的格雷码和n=k-1时的格雷码有关系,n=k的格雷码的前一半刚好是k-1时的格雷码,后一半,最高位变为1,低位的(0、1)排列刚好是k-1时格雷码的倒序。所以只需一个数组,更新时,只更新n=k时的后一半,即可。最后转化为List返回。

public class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> result=new ArrayList<>();
        int[] numbers=new int[(int)Math.pow(2,n)];
        numbers[0]=0;
        for(int i=1;i<=n;i++){
            int length=(int)Math.pow(2,i);
            for(int j=(int)Math.pow(2,i-1);j<length;j++){
                numbers[j]=numbers[length-1-j]+(1<<(i-1));
            }
        }
        for(int i=0;i<numbers.length;i++){
            result.add(numbers[i]);
        }
        return result;
    }
}



0 0
原创粉丝点击