Skip to content

Commit be54dbc

Browse files
committed
[LeetCode Sync] Runtime - 7 ms (68.25%), Memory - 21.1 MB (30.79%)
1 parent 2a2b35b commit be54dbc

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

Solutions/0089-gray-code/README.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<p>An <strong>n-bit gray code sequence</strong> is a sequence of <code>2<sup>n</sup></code> integers where:</p>
2+
3+
<ul>
4+
<li>Every integer is in the <strong>inclusive</strong> range <code>[0, 2<sup>n</sup> - 1]</code>,</li>
5+
<li>The first integer is <code>0</code>,</li>
6+
<li>An integer appears <strong>no more than once</strong> in the sequence,</li>
7+
<li>The binary representation of every pair of <strong>adjacent</strong> integers differs by <strong>exactly one bit</strong>, and</li>
8+
<li>The binary representation of the <strong>first</strong> and <strong>last</strong> integers differs by <strong>exactly one bit</strong>.</li>
9+
</ul>
10+
11+
<p>Given an integer <code>n</code>, return <em>any valid <strong>n-bit gray code sequence</strong></em>.</p>
12+
13+
<p>&nbsp;</p>
14+
<p><strong class="example">Example 1:</strong></p>
15+
16+
<pre>
17+
<strong>Input:</strong> n = 2
18+
<strong>Output:</strong> [0,1,3,2]
19+
<strong>Explanation:</strong>
20+
The binary representation of [0,1,3,2] is [00,01,11,10].
21+
- 0<u>0</u> and 0<u>1</u> differ by one bit
22+
- <u>0</u>1 and <u>1</u>1 differ by one bit
23+
- 1<u>1</u> and 1<u>0</u> differ by one bit
24+
- <u>1</u>0 and <u>0</u>0 differ by one bit
25+
[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
26+
- <u>0</u>0 and <u>1</u>0 differ by one bit
27+
- 1<u>0</u> and 1<u>1</u> differ by one bit
28+
- <u>1</u>1 and <u>0</u>1 differ by one bit
29+
- 0<u>1</u> and 0<u>0</u> differ by one bit
30+
</pre>
31+
32+
<p><strong class="example">Example 2:</strong></p>
33+
34+
<pre>
35+
<strong>Input:</strong> n = 1
36+
<strong>Output:</strong> [0,1]
37+
</pre>
38+
39+
<p>&nbsp;</p>
40+
<p><strong>Constraints:</strong></p>
41+
42+
<ul>
43+
<li><code>1 &lt;= n &lt;= 16</code></li>
44+
</ul>
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
class Solution:
2+
def grayCode(self, n: int) -> List[int]:
3+
return [i ^ (i >> 1) for i in range(2 ** n)]

0 commit comments

Comments
 (0)