mean python 1 liner, beat 95% also include more fair solution


  • 0
    V
    class Solution(object):
        def hammingWeight(self, n):
            """
            :type n: int
            :rtype: int
            """
            return bin(n).count('1')
    

    If you want to be a decent human being, then I guess you'd go with this approach:

    class Solution(object):
        def hammingWeight(self, n):
            """
            :type n: int
            :rtype: int
            """
            ct = 0
            mask = 1
            
            while n != 0:
                if mask & n:
                    ct += 1
                n = n >> 1
            
            return ct
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.