Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

89. 格雷编码 #26

Open
webVueBlog opened this issue Aug 31, 2022 · 0 comments
Open

89. 格雷编码 #26

webVueBlog opened this issue Aug 31, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

/**

  • @param {number} n
  • @return {number[]}
    */
    // 二进制数转格雷码
    // var grayCode = function(n) {
    // const ret = []
    // for (let i = 0; i < 1 << n; i++) {
    // ret.push((i >> 1) ^ i)
    // }
    // return ret
    // };

// 递归版
// var grayCode = function(n) {
// if (n === 0) return [0]
// if (n === 1) return [0, 1]

// let add = 1 << (n-1)
// let lastStatus = grayCode(n - 1)
// let res = [...lastStatus]

// for (let i = lastStatus.length - 1; i >= 0; i--) {
// res.push(lastStatus[i] + add)
// }
// return res
// }

var grayCode = function(n) {
let ans = [0]
let pre = 1
for (let i = 0; i < n; i++) {
for (let j = ans.length - 1; j >= 0; j--) {
ans.push(pre + ans[j])
}
pre <<= 1
}
return ans
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant