Day28- Counting Bits(Medium)
问题描述:
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.
给一个数num,找到从0-num这些数的二进制中分别有多少个1
Example:
Example 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
Note:
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.
这道题直接做的话就很简单,从0开始遍历num之前数,每个数都转化成二进制数,然后再遍历这个二进制数看看有多少个1就完了。因为想法太简单,所以官方要求我们不要用这个解法。限制我们的时间复杂度为O(n),空间复杂度为O(n).而且不想我们用语言内置的函数。
解法:
既然不让我们直接算,那这道题就只能用找规律了。官方给了我们提示,从2-3,4-7,8-15开始找。奈何找规律和二进制都是我的弱项啊。所以看了grandyang大神的博客,才知道有这么多规律。所以也不解释了。建议直接看大神的博客,我在下面贴两种解法的python实现吧。
#解法3
class Solution:
def countBits(self, num: int) -> List[int]:
result = [0]
for i in range(1,num + 1):
if i % 2 == 0:
result.append(result[i // 2])
else:
result.append(result[i // 2] + 1)
return result
#解法4
class Solution:
def countBits(self, num: int) -> List[int]:
result = [0] * (num + 1)
for i in range(1,num + 1):
result[i] = result[i & (i - 1)] + 1
return result
本文探讨了在给定非负整数范围内,计算每个数的二进制表示中1的数量的问题。通过寻找规律,提供了两种高效算法实现,避免了直接计算的高时间复杂度。
1211

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



