zoukankan      html  css  js  c++  java
  • 【leetcode】Gray Code (middle)

    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

    思路: Gray Code的意思就是n位的二进制序列,相邻两个只有一位不同。观察

    000 - 0
    001 - 1
    011 - 3
    010 - 2
    110 - 6
    111 - 7
    101 - 5
    100 - 4

    第0位的序列为 01 10 01 这样不断重复

    第1位的序列为 0011 1100

    第2位的序列为 11110000

    这样我们就找到了规律。

    我最开始是通过判段每次是第几位变化,通过异或得到新值。 每次第k为变化时满足 i = 2k + n*2(k+1)

    vector<int> grayCode(int n) {
            vector<int> ans;
            ans.push_back(0);
            if(n == 0)
                return ans;
    
            for(int i = 1; i < (1 << n); i++)
            {
                int bit_change = 0;
                for(int j = 0; j < n; j++)
                {
                    if(i % (1 << (j + 1)) - (1 << j) == 0)
                    {
                        bit_change = j; break;
                    }
                }
                int cur = (1 << bit_change);
                cur ^= ans.back();
                ans.push_back(cur);
            }
            return ans;
        }

    后来看其他人的发现更简单的方法

    vector<int> grayCode2(int n) {
            vector<int> ans;
            ans.push_back(0);
            if(n == 0)
                return ans;
    
            for(int i = 0; i < n; i++)
            {
                int inc = 1 << i;
                for(int j = ans.size() - 1; j >= 0; j--) //每次等第i - 1位正反序都存完毕时,第i位起始为0的情况也存储完了, 只需存储第i位起始为1并且低位倒序输出
                {
                    ans.push_back(ans[j] + inc);
                }
            }
            return ans;
        }
  • 相关阅读:
    区块链技术驱动金融.mobi
    ProcessExplorer 工具下载
    免费的论文查重网站
    接口可以继承接口吗?
    比较中的自动拆装箱
    Java语言中的异常处理
    Java类加载过程
    通过反射访问父类的私有成员
    final关键字详解
    MVC 控制台 +log4net 存入数据库
  • 原文地址:https://www.cnblogs.com/dplearning/p/4208623.html
Copyright © 2011-2022 走看看