Hamming Distance Solution


  • 0
    Z

    Approach 1. Bit operations and Count 1 numbers

    Intuition:
    Hamming Distance is the number of 1 in the XOR of A and B.

    class Solution(object):
        def hammingDistance(self, x, y):
            """
            :type x: int
            :type y: int
            :rtype: int
            """
            tmp = x ^ y
            # 求tmp中1的个数
            count = 0
            while tmp != 0:
                count += 1
                tmp = tmp & tmp-1
            return count
    

Log in to reply
 

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