Skip to content

Commit 6aa725e

Browse files
authored
Merge pull request #1685 from Abhinavcode13/patch-43
Create Hammingdistance.cpp
2 parents 44b0279 + a81b6b6 commit 6aa725e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Math/Hammingdistance.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
#include <vector>
2+
3+
class Solution {
4+
public:
5+
int totalHammingDistance(std::vector<int>& nums) {
6+
// Get the number of elements in the input vector
7+
int n = nums.size();
8+
// Initialize the variable to store the total Hamming distance
9+
int ans = 0;
10+
11+
// Iterate through each bit position (from 0 to 31)
12+
for (int i = 0; i < 32; i++) {
13+
// Initialize a variable to count the number of set bits at the current bit position
14+
int count = 0;
15+
16+
// Iterate through all elements in the vector
17+
for (int k = 0; k < n; k++) {
18+
// Count the number of set bits at the current bit position for each element
19+
count += (nums[k] >> i) & 1;
20+
}
21+
22+
// Update the total Hamming distance by adding the product of set bits and unset bits
23+
ans += count * (n - count);
24+
}
25+
26+
// Return the total Hamming distance
27+
return ans;
28+
}
29+
};
30+
31+
/*
32+
This program defines a Solution class with a totalHammingDistance method that calculates the total Hamming distance for the input vector nums. The outer loop iterates over each bit position (from 0 to 31), and the inner loop counts the number of set bits at that bit position for all elements in the vector. It then updates the ans variable by adding the product of the count of set bits and the count of unset bits at that position.
33+
34+
This code efficiently calculates the total Hamming distance for a vector of integers by considering each bit position separately. */

0 commit comments

Comments
 (0)