1ms Java solution


  • 0
    J

    One bit gray code 0,1
    Two bits gray code 00,01,11,10
    Three bits gray code 000,001,011,010,110,111,101,100
    See the three bits gray code, the first half numbers are the say of two bits numbers; if you add "1" to the front of the two bits numbers and reverse, you can the last half of numbers.
    See my code:

            List<Integer> ans = new ArrayList<Integer>();
            ans.add(0);
            if(n == 0) return ans;
            // ans.add(0); when n == 0 return [0]
            ans.add(1);
            for(int i = 1; i < n; i++){
                int size = ans.size();
                int mark = 1<<i;
                for(int j = size - 1; j >= 0 ; j--){
                    int num = ans.get(j);
                    num |= mark;
                    ans.add(num);
                }
            }
            return ans;
        }

Log in to reply
 

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