Simple Python Solution, without bit operations


  • 0
    T

    Simple Python Solution, without bit operations:

    class Solution(object):
        def hammingWeight(self, n):
            """
            :type n: int
            :rtype: int
            """
            ans=0
            while n>0:
                if n%2==1:
                    ans+=1
                n=n/2
            return ans
    

    This algorithm was inspired by "Short Division by Two with Remainder".


Log in to reply
 

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