Sponsored
Sponsored
This approach involves calculating the Hamming distance for each pair of numbers by comparing their binary representations. This naive method checks each bit position from the least significant bit to the most significant bit for each pair.
Time Complexity: O(n^2 * k) where n is the number of numbers and k is the number of bits per integer (32).
Space Complexity: O(1)
1#include <iostream>
2#include <vector>
3
4int hammingDistance(int x, int y) {
5 int xorValue = x ^ y, count = 0;
6 while (xorValue) {
7 count += xorValue & 1;
8 xorValue >>= 1;
9 }
10 return count;
11}
12
13int totalHammingDistance(std::vector<int>& nums) {
14 int totalDistance = 0, n = nums.size();
15 for (int i = 0; i < n; ++i) {
16 for (int j = i + 1; j < n; ++j) {
17 totalDistance += hammingDistance(nums[i], nums[j]);
18 }
19 }
20 return totalDistance;
21}
22
23int main() {
24 std::vector<int> nums = {4, 14, 2};
25 std::cout << totalHammingDistance(nums) << std::endl; // Output: 6
26 return 0;
27}
28
This C++ code follows the same logic. It uses the hammingDistance
function to count differing bits between two integers, and totalHammingDistance
to compute the total distance.
For each bit position, count how many numbers have that bit set. The number of pairs from two sets, one having the bit set and the other not, can be computed directly. This reduces the complexity significantly.
Time Complexity: O(n * k) where n is the array size and k is 32 (number of bits).
Space Complexity: O(1)
1#
This C code iterates through each bit position from 0 to 31. bitCount
keeps track of how many numbers have the current bit set. The Hamming distance contribution of this bit is given by bitCount * (numsSize - bitCount)
.