# Python one line solution

• ``````def hammingWeight(self, n):
return str(bin(n)).count('1')``````

• This is ruby version ; - )

``````def hamming_weight(n)
("%b" % n).chars.count{|c| c == '1'}
end``````

• str(bin(n))

What the...? Why are you applying `str` to a string?

• ``````class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
return len([i for i in range(32) if (1<<i)&n])
``````

Using bin() and count() smells a little tricky. Here is a more common one-line-python solution.
Hope is helps

• Right! bin(n).count('1') should be fine.

• here's my one line solution with recursive and operations

``````def hammingWeight(self, n, count=0):
return self.hammingWeight(n & n-1, count+1) if n!=0 else count
``````

• This post is deleted!

• @StefanPochmann bin(n).count('1') ,oh, I see,
bin(n) is already a string, no need to convert to string or list

• said in Python one line solution:

def hammingWeight(self, n):
return str(bin(n)).count('1')

i get wrong answer if i enter this print hammingWeight(1000000000001000000000000000000001)
can someine explain to me why?

• @999masks n should be an integer like 5, not bits

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