Simple Python Solution


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

  • 0
    K

    Hi, can you please explain why does this work?
    Thank you in advance!


  • 1
    T

    @kid821654 use weight as the counter for bit 1.
    n%2 will tell the value for lowest bit (2**0), in which case you can consider weight+=n%2 as weight=weight if lastBit==0 else weight+1
    check on the higher bit 2**1 and repeat. Hope this helps


Log in to reply
 

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