Beats 100% Python


  • 11
    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
    

  • 0

    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;
        }
    

  • 1
    N

    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.


  • 0
    M

    what does & do here?


  • 0
    G

    @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.


  • 0
    W

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


Log in to reply
 

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