-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
34 lines (27 loc) · 780 Bytes
/
Copy pathsolution.cpp
File metadata and controls
34 lines (27 loc) · 780 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
class Solution
{
public:
vector<string> graycode(int n)
{
vector<string> result;
// Total number of Gray Codes = 2^n
int total = 1 << n;
// Generate Gray Code for every number from 0 to 2^n - 1
for (int i = 0; i < total; i++)
{
// Gray Code formula
int gray = i ^ (i >> 1);
string binary = "";
// Convert gray number into binary string of length n
for (int bit = n - 1; bit >= 0; bit--)
{
if (gray & (1 << bit))
binary += '1';
else
binary += '0';
}
result.push_back(binary);
}
return result;
}
};