[LeetCode] Gray Code
2013-10-24 13:30
239 查看
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
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 问题描述:gray code是一种二进制数字系统,在这个系统中,两个相邻的数字之间只有一位不同。 给定一个非负整数n,n表示总共的位数,请打印出该gray code的序列,该序列必须以0开始。 后面给了一个n为2时的例子,如果要是能够利用这个例子来构造n值的序列就好了。通过分析可以得出,n的序列可以通过n-1的序列构造,将n-1的序列反向添加到原来的序列后面, 再原来的序列前加0,后来的序列前加1,其实也可以在后面加,但是OJ采用的是在前面加。
class Solution { public: vector<int> grayCode(int n) { // Note: The Solution object is instantiated only once and is reused by each test case. vector<int> vec; if(n == 0) { vec.push_back(0); return vec; } vec = grayCode(n-1); int i = 0; for(i = vec.size()-1; i >= 0; i--) { vec.push_back(vec.at(i) | (1<<(n-1))); } return vec; } };
相关文章推荐
- leetcode 89. Gray Code 按照index递归DFS解决 + Grey码生成公式 + 位运算直接计算
- LeetCode 89. Gray Code(格雷码)
- LeetCode 89. Gray Code
- 【题解】【排列组合】【回溯】【Leetcode】Gray Code
- [LeetCode] Gray Code
- LeetCode Gray Code
- [leetcode-89]Gray Code(c++)
- (java)leetcode-89:Gray Code
- Leetcode-89. Gray Code
- LeetCode89:Gray Code
- [leetcode] 89. Gray Code 解题报告
- leetcode 89:Gray Code
- [LeetCode] 033: Gray Code
- 【leetcode】89. Gray Code【java】
- [LeetCode]Gray Code
- [LeetCode] Gray Code
- LeetCode - Gray Code
- [LeetCode] Gray Code 解题报告
- LeetCode :: Gray Code[正确解答,真正考察点剖析]
- leetcode之Gray Code