My Output : [0,1,3,2,6,7,5,4,13,12,14,15,10,11,9,8]
Expected O/P: [0,1,3,2,6,7,5,4,13,12,14,15,10,11,9,8]
n = 4
while debugging it's doing the right index calculations but it's still adding 13 instead of 12 first.
Problem: An n-bit gray code sequence is a sequence of 2n integers where:
Every integer is in the inclusive range [0, 2n - 1], The first integer is 0, An integer appears no more than once in the sequence, The binary representation of every pair of adjacent integers differs by exactly one bit, and The binary representation of the first and last integers differs by exactly one bit. Given an integer n, return any valid n-bit gray code sequence.
My solution:
public static List<Integer> grayCode(int n) {
List<Integer> resuList = new ArrayList<Integer>();
resuList = callrecursion(n);
return resuList;
}
public static List<Integer> callrecursion(int n){
if (n==1) {
List<Integer> list = new ArrayList<Integer>();
list.add(0);
list.add(1);
return list;
}
List<Integer>result = new ArrayList<>();
List<Integer> list = callrecursion(n-1);
for (Integer integer : list) {
result.add(integer);
}
for (int i = list.size(); i >0; i--) {
int x = (int)Math.pow(2, n-1);
int sun = x+result.indexOf(i-1);
result.add(sun);
}
return result;
}