-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGrayCode.cpp
More file actions
executable file
·46 lines (39 loc) · 1020 Bytes
/
GrayCode.cpp
File metadata and controls
executable file
·46 lines (39 loc) · 1020 Bytes
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
//
// GrayCode.cpp
// leetcode
//
// Created by witwolf on 11/25/14.
// Copyright (c) 2014 witwolf. All rights reserved.
//
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
vector<int> grayCode(int n) {
vector<int> result;
result.push_back(0);
for(int i=0;i<n;++i){
size_t j = result.size();
while(j--){
int value = result[j];
value ^= 1<<i;
result.push_back(value);
}
}
return result;
}
};
int main(int argc,char **argv){
Solution s;
vector<int> result = s.grayCode(1);
copy(result.begin(),result.end(),ostream_iterator<int>(cout, " "));
cout << endl;
result = s.grayCode(2);
copy(result.begin(),result.end(),ostream_iterator<int>(cout, " "));
cout << endl;
result = s.grayCode(3);
copy(result.begin(),result.end(),ostream_iterator<int>(cout, " "));
cout << endl;
}