98. 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:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

Subscribe to see which companies asked this question

分析:在纸上多写几个找到规律之后再下手写代码就容易。

 给定位数,求其对应的格雷码。
* 如n=3
* 00 - 0
* 01 - 1
* 11 - 3
* 10 - 2
* 110 - 6
* 111 - 7
* 101 - 5
* 100 - 4
* 相比较于n=2时,n=3时相等于在n=2时的四个数字前分别加上0和对称地四个数字前分别加上1得到了其对应的八个数字。
* 所以,对应于已知i-1位的格雷码,就可以推出i位的格雷码。

/**
	 * 给定位数,求其对应的格雷码。
	 * 如n=3
	 * 00 - 0
	 * 01 - 1
	 * 11 - 3
	 * 10 - 2
	 * 110 - 6
	 * 111 - 7
	 * 101 - 5
	 * 100 - 4
	 * 相比较于n=2时,n=3时相等于在n=2时的四个数字前分别加上0和对称地四个数字前分别加上1得到了其对应的八个数字。
	 * 所以,对应于已知i-1位的格雷码,就可以推出i位的格雷码。
	 *  
	 */
	public List<Integer> grayCode(int n) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		if(n<0){
			return list;
		}
		list.add(0);//n=0时默认为一个格雷码
		/*已知i-1位的格雷码,就可以推出i位的格雷码。*/
		for(int i =1;i<=n;i++){
			int size = list.size();//先得到i-1位时的格雷码种类数
			int num = (int) Math.pow(2, i-1);
			for(int j=size-1;j>=0;j--){
				list.add(list.get(j)+num);
			}
		}
		
        return list;
    }

你可能感兴趣的:(98. Gray Code)