Skip to content

Commit f708e56

Browse files
committed
Add solution #89
1 parent 1d9485e commit f708e56

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy|
8282
86|[Partition List](./0086-partition-list.js)|Medium|
8383
88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy|
84+
89|[Gray Code](./0089-gray-code.js)|Medium|
8485
90|[Subsets II](./0090-subsets-ii.js)|Medium|
8586
93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium|
8687
94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy|

solutions/0089-gray-code.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* 89. Gray Code
3+
* https://leetcode.com/problems/gray-code/
4+
* Difficulty: Medium
5+
*
6+
* An n-bit gray code sequence is a sequence of 2n integers where:
7+
* - Every integer is in the inclusive range [0, 2n - 1],
8+
* - The first integer is 0,
9+
* - An integer appears no more than once in the sequence,
10+
* - The binary representation of every pair of adjacent integers differs
11+
* by exactly one bit, and
12+
* - The binary representation of the first and last integers differs by
13+
* exactly one bit.
14+
* Given an integer n, return any valid n-bit gray code sequence.
15+
*/
16+
17+
/**
18+
* @param {number} n
19+
* @return {number[]}
20+
*/
21+
var grayCode = function(n) {
22+
const result = [0];
23+
for (let i = 0; i < n; i++) {
24+
result.push(...result.map((v) => v | 1 << i).reverse());
25+
}
26+
return result;
27+
};

0 commit comments

Comments
 (0)