# Python 1 line 49ms

• ``````    def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count('1')
``````

• str.count('1') is to find how many '1's are in x ^ y, represented as string now, (with a '0b' in front). How is this working to find the distance between the two '1's?

• This is pretty pythonic, however the executing speed is about 23%, which is pretty slow. Not sure why.
I also tried to while loop through, which gives me about a speed of 45%.

• Don't know why, but convert it to string is faster than my solution, which only deals with int.

``````class Solution(object):
def hammingDistance(self, x, y):
z = x ^ y
count = 0
while z > 0:
count += z & 1
z >>= 1

return count
``````

It takes 52 ms.

• This post is deleted!

• My code takes 49ms as well. Maybe it is how python implements count().

``````class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
target = x ^ y
return Solution.count_ones(target)

@staticmethod
def round(num, mask, c):
return (num & mask) + (num >> (1 << c) & mask)

@staticmethod
def count_ones(num):
num = Solution.round(num, 0x55555555, 0)
num = Solution.round(num, 0x33333333, 1)
num = Solution.round(num, 0x0f0f0f0f, 2)
num = Solution.round(num, 0x00ff00ff, 3)
num = Solution.round(num, 0x0000ffff, 4)
return num
``````

• @ian34 i am really new to python. What is '^' in x ^ y. Are we subtracting both to find number of ones ?

• @bhavya12 Its logical Xor.

• @bhavya12 it is XOR operator, 0101 ^ 0001 = 0100 , in every bite same value get '1', different value get '0'

• @himon
it is diff that returns 1, and same 0.
you made it contrary.

• This post is deleted!

• return len(''.join(str(bin(x^y)).split('0')))-1

this one is much faster to count the '1's in a 0/1 string

• ``````class Solution(object):
def hammingDistance(self, x, y):
m = x ^ y
n = 0
while(m):
n += 1
m &= m -1
return n
``````

• @bhavya12 '^' is xor

• @bhavya12 It's an XOR. Imagine that it lines up x and y's bits and then keeps the ones that don't match up.

• Here's mine. Fastest submission at the time of this post at 28 ms:

``````class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
xor = x ^ y
count = 0
for _ in range(32):
count += xor & 1
xor = xor >> 1
return count
``````

• This post is deleted!

• @NoAnyLove said in Python 1 line 49ms:

=

Hi, friend,
Could you tell me how the '>>= ' operator works?
I cannot find information about it online.

Thank you

• @bhavya12 '^' is used to perform an XOR operation on two numbers in Python

• Try this

``````return len([i for i in format(x ^ y, 'b') if i=='1'])
``````

list comprehension in python is fast. But when I submit the same code again and again, I see the compute time changes, below is the best shot.

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