89. 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.

链接: http://leetcode.com/problems/gray-code/

6/4/2017

1ms, 43%

抄别人的,不需要按照十进制转为2进制,直接加10进制的数字(第8行),然后翻转后面的位就可以了。

 1 public class Solution {
 2     public List<Integer> grayCode(int n) {
 3         List<Integer> ret = new ArrayList<Integer>();
 4         if (n < 0) return ret;
 5         ret.add(0);
 6 
 7         for (int i = 0; i < n; i++) {
 8             int prefix = 1 << i; // 1, 2, 4
 9             for (int j = ret.size() - 1; j >= 0; j--) {
10                 ret.add(prefix + ret.get(j));
11             }
12         }
13         return ret;
14     }
15 }

别人的解法

The idea is simple. G(i) = i^ (i/2).

https://discuss.leetcode.com/topic/8557/an-accepted-three-line-solution-in-java

1 public List<Integer> grayCode(int n) {
2     List<Integer> result = new LinkedList<>();
3     for (int i = 0; i < 1<<n; i++) result.add(i ^ i>>1);
4     return result;
5 }

更多讨论

https://discuss.leetcode.com/category/97/gray-code

posted @ 2017-06-05 01:09  panini  阅读(145)  评论(0编辑  收藏  举报