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

338. 比特位计数 #82

Open
webVueBlog opened this issue Sep 6, 2022 · 0 comments
Open

338. 比特位计数 #82

webVueBlog opened this issue Sep 6, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

338. 比特位计数

Description

Difficulty: 简单

Related Topics: 位运算, 动态规划

给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。

示例 1:

输入:n = 2
输出:[0,1,1]
解释:
0 --> 0
1 --> 1
2 --> 10

示例 2:

输入:n = 5
输出:[0,1,1,2,1,2]
解释:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101

提示:

  • 0 <= n <= 105

进阶:

  • 很容易就能实现时间复杂度为 O(n log n) 的解决方案,你可以在线性时间复杂度 O(n) 内用一趟扫描解决此问题吗?
  • 你能不使用任何内置函数解决此问题吗?(如,C++ 中的 __builtin_popcount

Solution

Language: JavaScript

/**
 * @param {number} n
 * @return {number[]}
 */
// 动态规划
var countBits = function(n) {
    const bits = new Array(n+1).fill(0)
    for (let i = 1; i <= n; i++) {
        bits[i] = bits[i & (i-1)] + 1;
    }
    return bits;
}
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