5/30/2014

27. Gray Code

public class Solution {
    public ArrayList<Integer> grayCode(int n) {
        int size = 1<<n;
        ArrayList<Integer> res = new ArrayList<Integer> ();
       
        for (int i=0; i<size; i++) {
            res.add(i>>1 ^ i);
        }
       
        return res;
    }
}

1 条评论:

  1. 1. 把binary code直接转为gray code: 其实就等于 (1011 >> 1) ^ 1011 = 1110.
    2. 最大size,相当于2^n.

    回复删除