# 54 ms , python one line solution (edit : 48 ms now)

• ``````class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
return bin(n)[2:].zfill(32).count('1')
``````

Here is my one- line solution to the above problem. LMK if I optimize this further somewhere.

edit:

Above was my first solution, I quickly realized that I dont have to make it a 32 bit integer . I got rid of the zfill , and my solution is down to 48 ms. My solution is now as below.

``````class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
return bin(n)[2:].count('1')``````

• you even didn't need bin(n)[2:]
just bin(n) could work

• ``````def hammingWeight(self, n):
p = bin(n)
return sum((n=='1') for n in p[2:])
``````

generator list of n=='1' and then sum the array of true/false. Seems slightly faster than count.

• Hmm .. Well you are right , I didnt need to cut off the first two characters (ie) 0b - it doesn't contribute to the count of 1.

• Thanks for the review.

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