• 89. Gray Code (Bit)


    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.

    思路:

    二进制-->格雷码:如果二进制码字的第i位和i+1位相同,则对应的格雷码的第i位为0,否则为1。最高为之前可以看作还有一位0,即最高位是和0异或。

    *格雷码-->二进制:最左边一位不变,从左边第二位起,将每位与左边一位解码后的值异或,作为该位解码后的值。

    class Solution {
    public:
        vector<int> grayCode(int n) {
            vector<int> result;
            int size = 1 << n;
            for (int i =0; i< size; i++)
            {
                result.push_back(getGrayCode(i));
            }
            return result;
        }
        int getGrayCode(int binary)
        {
            return ((binary >> 1)^binary);
        }
    };
  • 相关阅读:
    前端开发者应该知道的 CSS 小技巧
    css3制作六边形图片
    css3 绘制优惠券
    flex css 布局
    js 微信分享
    JS判断移动设备最佳方法 并实现跳转至手机版网页
    ajax 提交成功页面跳转问题
    css相关tips
    无阻塞加载和defer、async
    常用排序算法
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5021283.html
Copyright © 2020-2023  润新知