Total Hamming Distance

Problem Id: 477 Difficulty: Medium


Intuition

Solution


class Solution:
    def totalHammingDistance(self, nums: List[int]) -> int:
        zeroes = [0] * 32
        ones = [0] * 32
        for num in nums:
            index = 0
            while index < 32:
                if num % 2:
                    ones[index] += 1
                else:
                    zeroes[index] += 1
                index += 1
                num = num >> 1
        ans = 0
        for i, j in zip(ones, zeroes):
            ans += i * j
        return ans