-
Notifications
You must be signed in to change notification settings - Fork 0
/
GrayCode.cc
109 lines (84 loc) · 1.93 KB
/
GrayCode.cc
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <vector>
#include <string>
#include <iostream>
using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;
#include <cstdlib>
using std::atoi;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x), next(nullptr){}
ListNode(std::initializer_list<int> vals):val(0), next(nullptr){
if(0 == vals.size()){
return;
}
auto p = vals.begin();
this->val = *p;
auto last = this;
for(++p; p != vals.end(); ++p){
last->next = new ListNode(*p);
last = last->next;
}
}
};
std::ostream& operator<<(std::ostream& os, ListNode *head){
for(; head; head = head->next){
os << head->val << " ";
}
return os;
}
#include <algorithm>
#include <cstring>
class Solution{
public:
void reverse_bit(unsigned &target, int idx){
auto mask = 1u << idx;
if (target & mask){
target &= (~mask);
}else{
target |= mask;
}
}
vector<int> grayCode(int n){
vector<int> ans;
if (!n){
return {};
}
unsigned now = 0;
unsigned mask = 0;
int cnt = 0;
for ( ; ; ){
ans.push_back(now);
if (cnt & 1){
int idx = 0;
for (idx = 0; idx < n; ++idx){
mask = 1u << idx;
if (mask & now){
break;
}
}
auto mbit = idx + 1;
if (mbit >= n){
break;
}
reverse_bit(now, mbit);
}else {
reverse_bit(now, 0);
}
++cnt;
}
return ans;
}
};
int main(){
Solution slu;
auto vec = slu.grayCode(0);
for(auto &item : vec){
cout << item << endl;
}
return 0;
}