foolish fly fox's blog

--Stay hungry, stay foolish.
--Forever young, forever weeping.



博客主页为:https://foolishflyfox.github.io/CsLearnNote/

477. Total Hamming Distance

https://leetcode.com/problems/total-hamming-distance/description/

Description

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Now your job is to find the total Hamming distance between all pairs of the given numbers.

Example:
Input: 4, 14, 2
Output: 6
Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.

Note:

Solution

class Solution(object):
    def totalHammingDistance(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        record = []
        len_nums = len(nums)
        ret, max_bits = 0, 0
        for n in nums:
            record.append(list(format(n, 'b'))[::-1])
            max_bits = max(max_bits, len(record[-1]))
        for i in range(max_bits):
            ones = 0
            for j in record:
                if i<len(j) and j[i]=='1': ones += 1
            ret += ones * (len_nums-ones)
        return ret