Gray Code

来源:互联网 发布:javascript实例300下载 编辑:程序博客网 时间:2024/05/16 09:41

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
这道题要用到Gray Code的定义:第i个序列为i^(i>>1)。

另外,C++里面的<<和>>之前不怎么用,需要学习下:

>> 表示右移,高位补符号位,这里右移一位表示除2;

<<表示左移,左移一位表示乘2,这里1<<n就是2的n次方。

vector<int> grayCode(int n){    int size = 1<<n;    vector<int> ans;    for(int i = 0; i < size; i++)        ans.push_back(i^(i>>1));    return ans;}




0 0
原创粉丝点击