-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgray_code.cpp
More file actions
48 lines (45 loc) · 1.06 KB
/
Copy pathgray_code.cpp
File metadata and controls
48 lines (45 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>
using namespace std;
/**
* Describe: 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, find the sequence of gray code. A gray code sequence must begin with 0
* and with cover all 2n integers.
*/
class Solution {
public:
vector<int> grayCode(int n) {
if (n <= 0) {
return vector<int>();
}
vector<int> rst(2, 0);
rst[0] = 0;
rst[1] = 1;
for (int i = 1; i < n; ++i) {
int tmp = 1 << i;
int j = (1 << i) - 1;
// Scan back
while (j >= 0) {
rst.push_back(tmp | rst[j]);
--j;
}
}
return rst;
}
};
int main() {
Solution so;
int n;
vector<int> test;
while (cin >> n) {
auto re = so.grayCode(n);
for (auto &ele : re) {
cout << ele << " ";
}
cout << endl;
}
return 0;
}