338. Counting Bits
2016-12-06 本文已影响3人
我是你的果果呀
Given a non negative integer numbernum. For every numbersiin the range0 ≤ i ≤ numcalculate the number of 1's in their binary representation and return them as an array.
Example:
Fornum = 5you should return[0,1,1,2,1,2].
Follow up:
It is very easy to come up with a solution with run timeO(n*sizeof(integer)). But can you do it in linear timeO(n)/possibly in a single pass?
Space complexity should beO(n).
Can you do it like a boss? Do it without using any builtin function like__builtin_popcountin c++ or in any other language.
二进制有个规律, 10, 100,1000,10000, 2,4,8,16 这些都会重新开始只有一个1
DP 公式 : dp[ i ] = dp[ i /2] + i & 1;
![](https://img.haomeiwen.com/i3805437/b3a124a3c0120c84.png)