Hamming Distance

异或一下然后统计1的个数就行了

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

Total Hamming Distance

可以直接对所有数的32个bit位进行逐个统计,每轮做一个位的,然后这一位的hamming distance就是0的个数乘以1的个数,一个简单的排列组合

class Solution(object):
    def totalHammingDistance(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        binList = [bin(x)[2:].zfill(32) for x in nums]
        result = 0
        for i in xrange(32):
            zero, one = 0, 0
            for binArray in binList:
                if binArray[i] == '0':
                    zero += 1
                else:
                    one += 1
            result += (zero * one)
        return result

results matching ""

    No results matching ""