Leetcode中的位操作

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

我的解法:39ms,打败了29.11%

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count =0
        flag=1
        item=1
        while(item!=33):
            item=item+1
            if(n&flag):
                     count=count+1
            flag=flag<<1
        return count
            

因为左移操作在python中位数是无限的!!详见http://www.cnblogs.com/zhengyun_ustc/archive/2009/10/14/shifting.html

所以我设置了item变量记录循环的次数,应该循环32次因为有32个位。所以时间复杂度是O(1)

最快的解法:

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        while n:
            count += 1
            n = n&(n-1)
        return count
            

解题思路总结:

把一个整数减去1,再和原整数做与运算,会把该整数最右边一个1变成0.那么一个整数的二进制表示中有多少个1就进行多少次这样的操作。

很多二进制的问题都可以用这个思路解决!!!

时间复杂度,空间复杂度分析:

扫描二维码关注公众号,回复: 1152789 查看本文章

The run time depends on the number of 11-bits in nn. In the worst case, all bits in nn are 11-bits. In case of a 32-bit integer, the run time is O(1)O(1).

The space complexity is O(1)O(1), since no additional space is allocated.


比如

十进制数20=二进制10100

输入:10100

10100 -00001=10011

10100&10011=10000

10000-00001=01111

10000&01111=00000



猜你喜欢

转载自blog.csdn.net/u011462357/article/details/79336685
今日推荐