(LeetCode)Counting Bits -- 求二进制中1的个数

来源:互联网 发布:是以知其将败 编辑:程序博客网 时间:2024/05/21 16:57

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的个数求出来,然后存放到位置中。

__author__ = 'jiuzhang'# -*- coding:utf-8 -*-class Solution(object):    def countBits(self, num):        if num == 0:            return [0]        res = [0]        bit = 0        tmp = num        while tmp > 0:            tmp /= 2            bit += 1        for i in xrange(bit - 1):            t_res = []            for j in res:                t_res.append(j + 1)            res = res + t_res        for i in res[:(num - pow(2, bit - 1)) + 1]:            res.append(i + 1)        return res



方法二:
        利用位运算,右移,并做与运算。
__author__ = 'jiuzhang'class Solution(object):    def countBits(self, num):        """        :type num: int        :rtype: List[int]        """        ans = [0]        for x in range(1, num + 1):            ans += ans[x >> 1] + (x & 1),        return ans



0 0