leetcodeのGray Code解題構想
1870 ワード
タイトルは以下の通りです.
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
Note: For a given n, a gray code sequence is not uniquely defined.
For example,
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が得られる.
このプロセスは、実際には、バイナリを1ビット右にシフトし、さらに自身と排他的にシフトすることに相当し、例えば、010を1ビット右にシフトして001を得る.001^010=011.
問題を解くには
(1)nから得られる全ての10進数の個数1<
(2)各数に対して、(i>>1)^iはiに対応するグレイコードである
コードは次のとおりです.
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が得られる.
このプロセスは、実際には、バイナリを1ビット右にシフトし、さらに自身と排他的にシフトすることに相当し、例えば、010を1ビット右にシフトして001を得る.001^010=011.
問題を解くには
(1)nから得られる全ての10進数の個数1<
(2)各数に対して、(i>>1)^iはiに対応するグレイコードである
コードは次のとおりです.
public class Solution {
public List grayCode(int n) {
List list = new ArrayList();
int size = 1<< n;
for(int i = 0; i < size; i++){
int greycode = (i >> 1) ^ i;
list.add(greycode);
}
return list;
}
}