Skip to content

Commit 8cdafd1

Browse files
author
applewjg
committed
Gray Code
Change-Id: I7fb8879b76fb1a712e5f63ed8e74209563c79d56
1 parent 5f0942a commit 8cdafd1

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

GrayCode.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
Author: King, [email protected]
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+
}

0 commit comments

Comments
 (0)