Counting Bits(统计比特位)

给定一个非负整数num,需要计算0到num范围内每个数二进制表示中1的个数,并以数组返回。讨论了两种方法:位操作法和动态规划法,其中位操作法在O(n)时间内完成,空间复杂度为O(n)。
摘要由CSDN通过智能技术生成

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的个数,并以数组的形式返回)

Example:
For num = 5 you should return [0,1,1,2,1,2].

Follow up:
● It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
● Space complexity should be O(n).
● Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

1.个人分析
先以最简单直接的思路去考虑,思路一:将i与1进行&运算,然后使1左移一位,重复该步骤直到1移动到最高位,即左移31次。思路二:i = i & (i-1)的结果是i最右边的1变为0,该表达式能够进行多少次就说明i中的1有多少个。

2.个人解法

<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值