天天看點

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 <code>[0,1,3,2]</code>. its gray code sequence is:

note:

for a given n, a gray code sequence

is not uniquely defined.

for example, <code>[0,2,3,1]</code> 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,是二進制的位數,任務是從0開始,下一個二進制數與上一個隻有其中一位不同,不可重複,将這些二進制數對應的十進制數放入數組,傳回這個資料。

ps,順序不唯一,leetcode的oj判斷符合要求即可。

舉個例子:

00 --&gt; 01 --&gt; 11

--&gt; 10

000

--&gt; 001 --&gt;

011 --&gt; 010 --&gt; 110 --&gt;

111 --&gt; 101 --&gt; 100

不知道衆位看官發現規律了沒,看n=2的例子,前兩個首位不變,變後面那一位,後兩個不看首位的1,後面的那位與前兩個是對稱的。

看n=3的例子的前4個,是n=2的例子在前面加個0而已,後四個與前四個對稱,把前面的0換成1。

知道對稱有什麼用呢?

有大用!

例如n=3的情形,你可以由前兩個推後兩個,這就有4個了,哈哈哈,由這四個推後四個,搞定!看代碼~