Gray Code

来源:互联网 发布:淘宝卖家三天不发货 编辑:程序博客网 时间:2024/06/16 01:18

一、问题描述

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 - 001 - 111 - 310 - 2

二、思路

求格雷码,我们用到了pow函数求出位数所能表示的最大数字,通过

i ^ (i / 2);

求出不同的值存入数组,而且存入数组中的数每次都只变动一位,所以符合我们的题目要求。

三、代码

class Solution {public:    vector<int> grayCode(int n) {        std::vector<int> v;        n = pow(2,n) - 1;        for(int i = 0; i <= n; ++i){            int temp = i ^ (i / 2);            v.push_back(temp);        }        return v;    }};

另在讨论区看到不用库函数的代码:

class Solution {    void utils(bitset<32>& bits, vector<int>& result, int k){        if (k==0) {            result.push_back(bits.to_ulong());        }        else {            utils(bits, result, k-1);            bits.flip(k-1);            utils(bits, result, k-1);        }    }public:    vector<int> grayCode(int n) {        bitset<32> bits;        vector<int> result;        utils(bits, result, n);        return result;    }};



0 0
原创粉丝点击