Formatted question description: https://leetcode.ca/all/477.html

477. Total Hamming Distance

Level

Medium

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:

  1. Elements of the given array are in the range of 0 to 10^9.
  2. Length of the array will not exceed 10^4.

Solution

For an integer that doesn’t exceed 10^9, it may have at most 32 bits.

For the i-th bit, if there are x numbers that have the i-th bit 1 and y numbers that have the i-th bit 0, then the total Hammindg distance for the i-th bit is x * y.

Therefore, loop over nums and for each bit, count the number of 1’s of the bit to obtain the total Hamming distance of the bit. Sum up the total Hamming distances of all the bits to obtain the total Hamming distance that is the result.

  • class Solution {
        public int totalHammingDistance(int[] nums) {
            int[] bits = new int[32];
            int length = nums.length;
            for (int num : nums) {
                int remaining = num;
                int index = 31;
                while (remaining > 0) {
                    bits[index] += remaining & 1;
                    remaining >>>= 1;
                    index--;
                }
            }
            int totalDistance = 0;
            for (int i = 0; i < 32; i++) {
                int curOnes = bits[i];
                totalDistance += curOnes * (length - curOnes);
            }
            return totalDistance;
        }
    }
    
  • Todo
    
  • class Solution(object):
      def totalHammingDistance(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        ans = 0
        mask = 1
        for j in range(0, 32):
          ones = zeros = 0
          for num in nums:
            if num & mask:
              ones += 1
            else:
              zeros += 1
          ans += ones * zeros
          mask = mask << 1
        return ans
    
    

All Problems

All Solutions