-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathGray Code.java
More file actions
45 lines (33 loc) · 1.01 KB
/
Gray Code.java
File metadata and controls
45 lines (33 loc) · 1.01 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
class Solution {
public List<Integer> grayCode(int n) {
if (n == 0) {
List<Integer> ans = Arrays.asList(0);
return ans;
}
List<String> arr = new ArrayList<>();
// Base case for 1
arr.add("0");
arr.add("1");
int c = 1;
while(c < n) {
for (int i=0;i<arr.size();i++) {
arr.set(i, "0" + arr.get(i));
}
int rev = arr.size()-1;
while (rev >= 0) {
arr.add("1" + arr.get(rev).substring(1));
rev--;
}
c++;
}
List<Integer> ans = getDecimalList(arr);
return ans;
}
public List<Integer> getDecimalList(List<String> arr) {
List<Integer> ans = new ArrayList<>();
for (String s : arr) {
ans.add(Integer.parseInt(s, 2));
}
return ans;
}
}