Counting Bits
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:
For num = 5 you should return [0,1,1,2,1,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
[0,1]
10,11,就是[0,1]加1
[100,101,110,111],就是前4个[0,1,10,11]加1
同理
所以只需使用前面的数据就行了
代码
class Solution {
public:
vector<int> countBits(int num) {
int i = 1;
vector<int> result;
if(num >= 0)
result.push_back(0);
if(num>=1)
result.push_back(1);
int end = pow(2,i+1);
while(num>=end-1)
{
int begin = pow(2,i);
int j=0;
for(int k = begin;k<=end-1;k++)
{
result.push_back(result[j]+1);
j++;
}
i++;
end = pow(2,i+1);
}
int j=0;
for(int k = pow(2,i);k<=num;k++)
{
result.push_back(result[j]+1);
j++;
}
return result;
}
};
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
min_num, max_num = 0, 1
arry = []
arry.append(0) # 0 is the first element
for i in range(1,num+1):
if i < max_num:
arry.append(arry[i-min_num]+1)
else:
arry.append(1)
min_num = max_num
max_num = max_num << 1
return arry
从0,2,4,8分段 因为都是1
然后 9的末尾就是9-8 =1相同 8就是max_num
837



被折叠的 条评论
为什么被折叠?



