美文网首页动态规划
338. Counting Bits

338. Counting Bits

作者: 我是你的果果呀 | 来源:发表于2016-12-06 06:40 被阅读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;

相关文章

网友评论

    本文标题:338. Counting Bits

    本文链接:https://www.haomeiwen.com/subject/rtglmttx.html