package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * https://leetcode.com/problems/circular-permutation-in-binary-representation/
 */
public class Problem1238 {
    public List<Integer> circularPermutation(int n, int start) {
        List<Integer> answer = new ArrayList<>();
        answer.add(start);
        // TODO
        return answer;
    }

    private static int binaryToGray(int n) {
        // https://en.wikipedia.org/wiki/Gray_code
        return n ^ (n >> 1);
    }

    public static void main(String[] args) {
        Problem1238 prob = new Problem1238();
        System.out.println(prob.circularPermutation(2, 3)); // [3,2,0,1]
        System.out.println(prob.circularPermutation(3, 2)); // [2,6,7,5,4,0,1,3]
    }
}

@@ -40,16 +40,46 @@
 ayList;%0A
+import java.util.Collections;%0A
 import j
@@ -336,95 +336,100 @@
     
-answer.add(start);%0A        // TODO%0A        return answer;
+int index = 0;%0A        for (int i = 0; i %3C Math.pow(2, n); i++) %7B
 %0A    
-%7D%0A%0A
     
-private static int
+    int grayCode =
  bin
@@ -443,15 +443,10 @@
 ay(i
-nt n) %7B
+);
 %0A   
@@ -454,331 +454,320 @@
     
-// https://en.wikipedia.org/wiki/Gray_code%0A        return n %5E (n %3E%3E 1);%0A
+    if (grayCode == start) %7B%0A                index = i;%0A        
     %7D%0A
-%0A
     
-public static void main(String%5B%5D args) %7B%0A        Problem1238 prob = new Problem1238();%0A        System.out.println(prob.circularPermutation(2, 3)); // %5B3,2,0,1%5D%0A        System.out.println(prob.circularPermutation(3, 2)); // %5B2,6,7,5,4,0,1,3%5D
+        answer.add(grayCode);%0A        %7D%0A        Collections.rotate(answer, -index);%0A        return answer;%0A    %7D%0A%0A    private static int binaryToGray(int n) %7B%0A        // https://en.wikipedia.org/wiki/Gray_code%0A        return n %5E (n %3E%3E 1);
 %0A   

Solve problem 1238