Skip to content

Commit a81b6b6

Browse files
Update Hammingdistance.cpp
1 parent 1d6a57f commit a81b6b6

File tree

1 file changed

+28
-8
lines changed

1 file changed

+28
-8
lines changed

Math/Hammingdistance.cpp

+28-8
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,34 @@
1-
lass Solution {
1+
#include <vector>
2+
3+
class Solution {
24
public:
3-
int totalHammingDistance(vector<int>& nums) {
4-
int n=nums.size(), ans=0;
5-
for(int i=0;i<32;i++){
6-
int count=0;
7-
for(int k=0;k<n;k++){
8-
count += (nums[k]>>i)&1;
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;
920
}
10-
ans += count*(n-count);
21+
22+
// Update the total Hamming distance by adding the product of set bits and unset bits
23+
ans += count * (n - count);
1124
}
25+
26+
// Return the total Hamming distance
1227
return ans;
1328
}
1429
};
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)