public boolean grayCode(byte a, byte b) {
   byte x = (byte) (a ^ b);
   int count = 0;
   while (x != 0) {
    count++;
    x = (byte) (x&(x-1));
  }
  return  count == 1 ? 1 : 0;
} 




//All we need to do is to add an '1' to the top digit of the binary string and reversely added the new number to the list.
public ArrayList<Integer> grayCode(int n) {
       ArrayList<Integer> res = new ArrayList<Integer>();
       res.add(0);
       for (int i = 0; i < n; i++) {
           for (int j = res.size() - 1; j >= 0; j--) {
               res.add(res.get(j) + (1 << i));
           }
       }
       return res;
    }


0 ^ 0 = 0
1 ^ 0 = 1
10 ^ 01 = 11
11 ^ 01 = 10

public List<Integer> grayCode(int n) {
    int count = (int)Math.pow(2,n);
    List<Integer> res = new ArrayList<>();
    for(int i = 0; i < count; i++){
        res.add((i) ^ (i >> 1));
    }
    return res;
}

results matching ""

    No results matching ""