一、题目
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.
二、题目大意
给定一个非负整数num。对于0≤i≤num范围内的每个数字i,计算其二进制表示形式中的1个数,并将其作为数组返回。
三、解题思路
巧用位运算
四、代码实现
const countBits = num => {
const dp = []
dp[0] = 0
for (let i = 1; i <= num; i++) {
dp[i] = dp[i >> 1] + (i & 1)
}
return dp
}
如果本文对您有帮助,欢迎关注微信公众号,为您推送更多大前端相关的内容, 欢迎留言讨论,ε=ε=ε=┏(゜ロ゜;)┛。
![](https://user-images.githubusercontent.com/17818249/42768887-3afba45e-8953-11e8-920b-b5ce001adf81.jpg)
您还可以在这些地方找到我: