1
+ /*
2
+ Author: King, wangjingui@outlook.com
3
+ Date: Dec 27, 2014
4
+ Problem: Gray Code
5
+ Difficulty: Easy
6
+ Source: https://oj.leetcode.com/problems/gray-code/
7
+ Notes:
8
+ The gray code is a binary numeral system where two successive values differ in only one bit.
9
+ Given a non-negative integer n representing the total number of bits in the code, print the
10
+ sequence of gray code. A gray code sequence must begin with 0.
11
+ For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
12
+ 00 - 0
13
+ 01 - 1
14
+ 11 - 3
15
+ 10 - 2
16
+ Note:
17
+ For a given n, a gray code sequence is not uniquely defined.
18
+ For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
19
+ For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.
20
+
21
+ Solution: Refer to http://en.wikipedia.org/wiki/Gray_code.
22
+ */
23
+ public class Solution {
24
+ public List <Integer >grayCode (int n ) {
25
+ ArrayList <Integer >res =new ArrayList <Integer >();
26
+ for (int i =0 ;i <1 <<n ; ++i )
27
+ res .add ((int )((i >>1 ) ^i ));
28
+ return res ;
29
+ }
30
+ }