From 7e6d871c61e6483ec7efb9882fce8770b6b373fb Mon Sep 17 00:00:00 2001 From: Wen <409053122@qq.com> Date: Wed, 28 Jun 2023 16:07:17 +0800 Subject: [PATCH] =?UTF-8?q?feat:[89]=20=E6=A0=BC=E9=9B=B7=E7=BC=96?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/leecode/javascript/89.格雷编码.js | 47 +++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 src/leecode/javascript/89.格雷编码.js diff --git a/src/leecode/javascript/89.格雷编码.js b/src/leecode/javascript/89.格雷编码.js new file mode 100644 index 0000000..fd6936e --- /dev/null +++ b/src/leecode/javascript/89.格雷编码.js @@ -0,0 +1,47 @@ +/* + * @lc app=leetcode.cn id=89 lang=javascript + * + * [89] 格雷编码 + */ + +// @lc code=start +/** + * @param {number} n + * @return {number[]} + */ +var grayCode = function (n) { + const zeroSeq = [["0"]]; + const oneSeq = [["1"]]; + for (let index = 1; index < n; index++) { + const zeroPush = []; + const onePush = []; + for (const str of zeroSeq[index-1]) { + zeroPush.push("0" + str); + } + for (const str of oneSeq[index-1]) { + zeroPush.push("0" + str); + } + for (const str of oneSeq[index-1].slice().reverse()) { + onePush.push("1" + str); + } + for (const str of zeroSeq[index-1].slice().reverse()) { + onePush.push("1" + str); + } + zeroSeq.push(zeroPush); + oneSeq.push(onePush); + } + const ret = []; + if (n === 0) { + ret.push(0); + } else { + for (const str of zeroSeq[n-1]) { + ret.push(parseInt(str, 2)); + } + for (const str of oneSeq[n-1]) { + ret.push(parseInt(str, 2)); + } + } + return ret; +}; +console.log(grayCode(3)); +// @lc code=end