Bit operate in Python(44ms)


  • -2
    R
    class Solution(object):
    def hammingWeight(self, n):
        weight = 0
        if n == 0:
            return n
        while n >= 1:
            remainder = n % 2
            n = n / 2
            if remainder != 0:
                weight += 1
        return weight

  • -2
    T

    class Solution(object):
    def hammingWeight(self, n):
    """
    :type n: int
    :rtype: int
    """
    if n==0 or n==1:
    return n
    r=[]
    while(n>0):
    r.append(n%2)
    n/=2
    return sum(r)


  • 0
    R

    if you tap four times, your code could be more viewable.


Log in to reply
 

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