leetcode 之 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.
題目意思就是將n位的二進位制碼轉變成相應的格雷碼。下面給出二進位制碼和格雷碼的對應,舉例n=3,從中找到轉化的規律十進位制 二進位制 格雷碼
0 000 000
1 001 001
2 010 011
3 011 010
4 100 110
5 101 111
6 110 101
7 111 100
二進位制轉格雷碼的規律為:先在二進位制最左邊新增0,舉例 010 -> 0010, 再前一位與後一位異或,得到後一位的格雷碼值,即:0^0=0; 0^1=1; 1^0=1; 因此得到格雷碼011。
該過程其實就相當於將二進位制右移一位,再與自身異或,舉例: 010 右移一位得到 001; 001^010=011。
所以解題思路就是:
(1)根據n得到所有10進位制的個數 1<<n
(2)對每個數,(i >>1)^i 即為i對應的格雷碼
程式碼如下:
public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> list = new ArrayList<Integer>();
int size = 1<< n;
for(int i = 0; i < size; i++){
int greycode = (i >> 1) ^ i;
list.add(greycode);
}
return list;
}
}