Gray Code

★★★☆☆

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2

Note: mirror from prev, add 1 to the left of each of element in the mirror part

 00, 01, 11, 10 (result of n == 2)
 00, 01, 11, 10, 10, 11, 01, 00
                 --------------> mirror from previous
000,001,011,010,110,111,101,100> add 1 to the left of the mirror part
public List<Integer> grayCode(int n) {
    List<Integer> res = new ArrayList<Integer>(Arrays.asList(0));
    for (int i = 0; i < n; ++i) {
        int prevSz = res.size();
        for (int j = 0; j < prevSz; ++j) 
            res.add(res.get(prevSz - 1 - j) | (1 << i));
    }
    return res;
}

results matching ""

    No results matching ""