python--leetcode338. 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.

Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.

题目意思是给定一个数字,让你返回一个list。list中是所有小于这个数字的数的二进制形式中1的个数。

这题我有点不爽...这是一个数学问题,我的解法时间复杂度没有符合O(n)的要求,所以我要很不爽地写上三个解法,最后一个符合要求。

第一种,用python库解决:

class Solution(object):
 
    def countBits(self,num):
        res=[]
        for i in range(num+1):
           nbin = bin(i & 0xffffffff)
           res.append(nbin.count('1'))
        return res

s=Solution()
print(s.countBits(5))
简单明了,位运算。

第二种,手动求解:

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        res=[]
        for i in range(num+1):
            count=0
            while i>0:
                if i%2==1: count+=1
                i=i//2
            res.append(count)
        return res


s=Solution()
print(s.countBits(5))
第三种,既时间复杂度符合O(n)算法:

def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        
        iniArr = [0]
        if num > 0:
            amountToAdd = 1
            while len(iniArr) < num + 1:
                iniArr.extend([x+1 for x in iniArr])
        
        return iniArr[0:num+1]






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哎呦不错的温jay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值