# Beats 100% Python

• ``````class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
x = x ^ y
y = 0
while x:
y += 1
x = x & (x - 1)
return y
``````

• nice solution, it's the best of them as far as I can tell.
Here's the same in C#

``````    public int HammingDistance(int x, int y)
{
int count = 0;
int diff = x ^ y;
while (diff != 0)
{
count++;
diff = diff & (diff - 1);
}
return count;
}
``````

• Smart solution. The `x & (x-1)` trick makes sure it only iterates the fewest loop. Reusing `x` and `y` also improves a few ms in Python.

• what does & do here?

• @munkhjargal it's a bitwise AND operator. Basically means 0 will dominate a slot if it exists: e.g. 0011 & 0101 = 0001.

Definitely a cool solution, but perhaps not super Pythonic because what's happening is pretty obscure.

• quite similar to mine. but only beats about half of all submissions :(
found this post and found it's the same as mine

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