Leetcode89. Gray Code

来源:互联网 发布:php cli模式 编辑:程序博客网 时间:2024/06/10 04:42

题目: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

格雷码是一个二进制数字系统,其中两个连续的值只有一位不同。
给定代表代码中总位数的非负整数n,打印格雷码序列。 格雷码序列必须以0开头。
例如,给定n = 2,返回[0,1,3,2]。

普通二进制码与格雷码可以互相转换:
2位元格雷码 二进制码
00          00
01          01
11          10
10          11
3位元格雷码 二进制码
000         000
001         001
011         010
010         011
110         100
111         101
101         110
100         111
二进制码->格雷码:最左边一位不变,从最左位起,依次将每一位与右边一位异或(XOR);
                  例:二进制码(010)->首位0照写->位异或(0 XOR 1->1;1 XOR 0->1;补首位)-> 格雷码(011)
                  G:格雷码 B:二进位码  G(N) = B(n+1) XOR B(n)
格雷码-〉二进制码:二进制最高位补零,二进位码第n位 =二进位码第(n+1)位异或格雷码第n位。
                  例:格雷码(011)->二进制(0 b2 b1 b0)->b2=0 XOR 0=0,b1=b2 XOR 1=1,b0=b1 XOR 1=0->格雷码(010)
                  G:格雷码 B:二进位码  B(N) = B(n+1) XOR G(n) 

下面可以开始编写代码:n位共有2^n个格雷码,将0~2^(n-1)个数从二进制转变为格雷码:

代码如下:

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(i^i>>1);        }        return result;    }};