Leetcode 第338题
文章目录
题目描述
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.
Example 1:
|
|
Example 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, 这个问题可以用分治法来解决。
令非负整数 N 中的1有 f(N) 个,N的个位数为 S(N)
$$ f(N) = f(N/2) + (S(N) == 1) $$ $$ … $$ $$ f(0) = 0 $$
根据上述的思路,我们可以写出如下的伪代码:
|
|
这个题需要求1..N
每个数的二进制表示中1的个数,所以我们可以将中间结果存储起来,没必要每个数都从0开始运算一遍。
代码
- solution.go
|
|
- solution_test.go
|
|