美文网首页
89. Gray Code

89. Gray Code

作者: juexin | 来源:发表于2017-01-05 16:16 被阅读0次

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.

public class Solution {
    public List<Integer> grayCode(int n) {
        List<Integer> arr = new ArrayList<Integer>();
        int i = 1 << n;
   //     System.out.println(i);
        int k = 0;
        while(k < i)
        {
            arr.add(k^(k>>1));  //  原始数据 + 原始数据>>1 = 格雷码
            k++;
        }
        return arr;
    }
}

相关文章

  • [Math]89. Gray Code

    分类:Math 时间复杂度: O(n) 空间复杂度: O(n) 89. Gray Code The gray co...

  • 89. Gray Code

    这题做的很虚, 嗯,居然过了 题目中的一种做法的复现: 打死我吧,打死我我可能会想出来这种办法

  • 89. Gray Code

    题目描述:给非负整数 n 表示二进制位数,输出所有的 n 位格雷码,以0开始。 分析:时间复杂度O(2^n),空间...

  • 89. Gray Code

  • 89. Gray Code

    i = i^(i/2) 别问我咋的出来的, 不知道。。。

  • 89. Gray Code

    The gray code is a binary numeral system where two succes...

  • 89. Gray Code

    题目链接 https://leetcode.com/problems/gray-code/ 思路 假设n-1已经求...

  • Leetcode 89. Gray Code

    文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. S...

  • Leetcode 89. Gray Code

    The gray code is a binary numeral system where two succes...

  • LeetCode笔记:89. Gray Code

    问题: The gray code is a binary numeral system where two su...

网友评论

      本文标题:89. Gray Code

      本文链接:https://www.haomeiwen.com/subject/uruzvttx.html