338. Counting Bits

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;


338. Counting Bits_第1张图片

你可能感兴趣的:(338. Counting Bits)