6-Line Java Solution, Very Concise

  • 13

    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 List<Integer> grayCode(int n) {
        List<Integer> ans = new ArrayList<>();
        for(int i = 0; i < n ; i++)
            for(int j = ans.size()-1; j>=0; j--)
        return ans;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.