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.个人解法
<