美文网首页
LeetCode每日一题:格雷码

LeetCode每日一题:格雷码

作者: yoshino | 来源:发表于2017-05-16 15:37 被阅读56次

    问题描述

    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.

    问题分析

    这题是一道概念题,主要考察格雷码的概念,稍微百度一下就能够知道答案了

    在一组数的编码中,若任意两个相邻的代码只有一位二进制数不同,则称这种编码为格雷码(Gray Code),格雷码能保证最大数和最小数之间也只差一位

    • 每次右移一位再与原来取异或即可

    代码实现

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

    相关文章

      网友评论

          本文标题:LeetCode每日一题:格雷码

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