Skip to content

Commit 918bdf2

Browse files
Merge pull request #118 from walkerrandolphsmith/feature/89
solve problem
2 parents a828104 + 6fa9366 commit 918bdf2

2 files changed

Lines changed: 55 additions & 0 deletions

File tree

leet-code/89-gray-code/README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# 89-gray-code
2+
3+
An n-bit gray code sequence is a sequence of 2n integers where:
4+
5+
Every integer is in the inclusive range [0, 2n - 1],
6+
The first integer is 0,
7+
An integer appears no more than once in the sequence,
8+
The binary representation of every pair of adjacent integers differs by exactly one bit, and
9+
The binary representation of the first and last integers differs by exactly one bit.
10+
Given an integer n, return any valid n-bit gray code sequence.
11+
12+
Example 1:
13+
14+
Input: n = 2
15+
Output: [0,1,3,2]
16+
Explanation:
17+
The binary representation of [0,1,3,2] is [00,01,11,10].
18+
- 00 and 01 differ by one bit
19+
- 01 and 11 differ by one bit
20+
- 11 and 10 differ by one bit
21+
- 10 and 00 differ by one bit
22+
[0,2,3,1] is also a valid gray code sequence, whose binary representation is [00,10,11,01].
23+
- 00 and 10 differ by one bit
24+
- 10 and 11 differ by one bit
25+
- 11 and 01 differ by one bit
26+
- 01 and 00 differ by one bit
27+
Example 2:
28+
29+
Input: n = 1
30+
Output: [0,1]
31+
32+
33+
Constraints:
34+
35+
1 <= n <= 16

leet-code/89-gray-code/index.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number} n
3+
* @return {number[]}
4+
*/
5+
var grayCode = function(n) {
6+
const numberOfBits = 1 << n; // 2^n
7+
return Array.from({ length: numberOfBits }, (_, i) => encode(i));
8+
};
9+
10+
function encode(n) {
11+
return xor(n, dropLeastSignificantBit(n))
12+
}
13+
14+
function dropLeastSignificantBit(n) {
15+
return n >> 1
16+
}
17+
18+
function xor(x, y) {
19+
return x ^ y
20+
}

0 commit comments

Comments
 (0)