-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
29 lines (22 loc) · 803 Bytes
/
Copy pathsolution.java
File metadata and controls
29 lines (22 loc) · 803 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
class Solution {
public ArrayList<String> graycode(int n) {
ArrayList<String> result = new ArrayList<>();
// Total number of Gray Codes = 2^n
int total = 1 << n;
// Generate Gray Code for every number
for (int i = 0; i < total; i++) {
// Gray Code formula
int gray = i ^ (i >> 1);
StringBuilder binary = new StringBuilder();
// Convert gray number into binary string of length n
for (int bit = n - 1; bit >= 0; bit--) {
if ((gray & (1 << bit)) != 0)
binary.append('1');
else
binary.append('0');
}
result.add(binary.toString());
}
return result;
}
}