zoukankan      html  css  js  c++  java
  • 腾讯//格雷编码

    格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。

    给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。

    示例 1:

    输入: 2
    输出: [0,1,3,2]
    解释:
    00 - 0
    01 - 1
    11 - 3
    10 - 2
    
    对于给定的 n,其格雷编码序列并不唯一。
    例如,[0,2,3,1] 也是一个有效的格雷编码序列。
    
    00 - 0
    10 - 2
    11 - 3
    01 - 1

    示例 2:

    输入: 0
    输出: [0]
    解释: 我们定义格雷编码序列必须以 0 开头。
         给定编码总位数为 n 的格雷编码序列,其长度为 2nn = 0 时,长度为 20 = 1。
         因此,当 n = 0 时,其格雷编码序列为 [0]。
    
    class Solution {
    public:
        
        /*
         * @param n: a number
         * @return: Gray code
         */
        vector<int> grayCode(int n) {
            // write your code here
            if (n <= 0) {
                return vector<int>(1, 0);
            }
     
            vector<string> strs = grayCodeOfString(n);
            vector<int> result;
            for (int i = 0; i < strs.size(); i++) {
                result.push_back(bitStringToInt(strs[i]));
            }
            return result;
        }
     
        vector<string> grayCodeOfString(int n) {
            vector<string> strs(pow(2, n), "");
            if (n == 1) {
                strs[0] = "0";
                strs[1] = "1";
                return strs;
            }
            vector<string> last = grayCodeOfString(n - 1);
     
            for (int i = 0; i < last.size(); i++) {
                strs[i] = "0" + last[i];
                strs[strs.size() - 1 - i] = "1" + last[i];
            }
            return strs;
        }
     
        int bitStringToInt(string str) {
            int result = 0, pow = 1;
            for (int i = str.size() - 1; i >= 0; i--) {
                result += ((str[i] - '0') * pow);
                pow *= 2;
            }
            return result;
        }
    };
    
    class Solution {
    public:
        
        /*
         * @param n: a number
         * @return: Gray code
         */
        vector<int> grayCode(int n) {
            int size = 1<<n;
            vector<int> res;
            for(int i = 0; i < size; i++){
                int graycode = i^(i>>1);
                res.push_back(graycode);
            }
            return res;
        }
           
    };
  • 相关阅读:
    SpringBoot中mybatis配置自动转换驼峰标识没有生效
    spring boot 配置动态刷新
    读书笔记——spring cloud 中 HystrixCommand的四种执行方式简述
    spring cloud 加入配置中心后的 部分 配置文件优先级
    spring boot 服务 正确关闭方式
    CentOS 6.4 安装 rabbitmq(3.6.15)
    CentOS 6.4 配置DNS
    CentOS 查看系统版本号
    服务治理的技术点
    【转载】C#中使用Average方法对List集合中相应元素求平均值
  • 原文地址:https://www.cnblogs.com/strawqqhat/p/10602440.html
Copyright © 2011-2022 走看看