-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gray to binary equivalent
53 lines (40 loc) · 1.07 KB
/
Gray to binary equivalent
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
//Gray to binary equivalent
import java.io.*;
import java.util.*;
class Solution{
public static int grayToBinary(int n) {
ArrayList<Integer> temp = new ArrayList<>();
while(n != 0) {
if((n & 1) == 1) {
temp.add(1);
}
else {
temp.add(0);
}
n >>= 1;
}
Collections.reverse(temp);
for(int i = 1; i < temp.size(); i++) {
temp.set(i, temp.get(i - 1) ^ temp.get(i));
}
int ans = 0, j = 0;
for(int i = temp.size() - 1; i >= 0; i--) {
if(temp.get(i) == 1) {
ans += Math.pow(2, j);
}
j++;
}
return ans;
}
}
class GFG {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
Solution obj = new Solution();
System.out.println(obj.grayToBinary(n));
}
}
}