您的位置:首页 > 其它

LeetCode OJ:Gray Code(格林码)

2015-11-21 16:34 363 查看
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

看着好像很难的样子,但是实际上就是一个二进制码到格林吗的转换而已,代码如下(这个本科的时候好像学过,但是不记得了,看了下别人的):

class Solution {
public:
vector<int> grayCode(int n) {
int total = 1 << n;
vector<int> ret;
for(int i = 0; i < total; ++i){
ret.push_back(i>>1^i);
}
return ret;
}
};


java版本的代码如下所示:

public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> ret = new ArrayList<Integer>();
int num = 1 << n;
for(int i =0 ; i< num; ++i){
ret.add(i>>1^i);
}
return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: