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;


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容