LeetCode刷题:89. Gray Code

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/seagal890/article/details/89441326

LeetCode刷题:89. Gray Code

原题链接:https://leetcode.com/problems/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.

Example 1:

Input: 2
Output: [0,1,3,2]
Explanation:
00 - 0
01 - 1
11 - 3
10 - 2

For a given n, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.

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

Input: 0
Output: [0]
Explanation: We define the gray code sequence to begin with 0.
             A gray code sequence of n has size = 2n, which for n = 0 the size is 20 = 1.
             Therefore, for n = 0 the gray code sequence is [0].

算法设计

package com.bean.algorithm.basic;

import java.util.ArrayList;
import java.util.List;

public class GrayCode {

	/*
	 * If n is 0 then add 0 to the list and return. 
	 * for n > 0: add 0, 1 initially.
	 * In every iteration, iterate over the list in reverse direction and 
	 * add 1 before that number in bit representation using this statement
	 * list.add(list.get(--size) ^ (1 << i)) 
	 * 1: add 0(0), 1(1) 
	 * 2: 0(0), 1(1), 11(3), 10(2) 
	 * 3: 0(0), 1(1), 11(3), 10(2), 110(6), 111(7), 101(5), 100(4) 
	 * and so on.
	 */

	public static List<Integer> grayCode(int n) {
		List<Integer> list = new ArrayList<>();

		list.add(0);
		if (n == 0)
			return list;
		list.add(1);

		for (int i = 1; i < n; i++) {
			int size = list.size();
			while (size > 0) {
				list.add(list.get(--size) ^ (1 << i));
			}
		}

		return list;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int n = 2;
		List<Integer> list = grayCode(n);

		System.out.println(list);

	}

}

程序运行结果:

[0, 1, 3, 2]

猜你喜欢

转载自blog.csdn.net/seagal890/article/details/89441326
今日推荐