LeetCode 191 – Python 3 (Week 06 – 02)

Solution 1 (Same to No. 190)

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
            
        ans = 0
        for i in range(32):
            ans += (n & 1)
            n = n >> 1
        return ans

Time complexity is O(1). Space complexity is O(1).

Solution 2

n: xxxxxxxx1 ans = 0
n-1: xxxxxxx0
n = n&(n-1): xxxxxxx10 xxx(n of 0) ans = 1 (one 1)
n-1: xxxxxxx01 or xxx0(n of 1)
n = n&(n-1): xxxxxxx00 or xxx(n of 0) ans = 2 (one 1)
untile
n = 0
class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
            
        ans = 0
        while n:
            ans += 1
            n &= (n - 1)
        return ans

Time complexity is O(1). Space complexity is O(1).

Leave a comment

Design a site like this with WordPress.com
Get started