Skip to content

Commit b48a4f2

Browse files
committed
Add solution #477
1 parent fce23e1 commit b48a4f2

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,7 @@
382382
474|[Ones and Zeroes](./0474-ones-and-zeroes.js)|Medium|
383383
475|[Heaters](./0475-heaters.js)|Medium|
384384
476|[Number Complement](./0476-number-complement.js)|Easy|
385+
477|[Total Hamming Distance](./0477-total-hamming-distance.js)|Medium|
385386
482|[License Key Formatting](./0482-license-key-formatting.js)|Easy|
386387
485|[Max Consecutive Ones](./0485-max-consecutive-ones.js)|Easy|
387388
486|[Predict the Winner](./0486-predict-the-winner.js)|Medium|
+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* 477. Total Hamming Distance
3+
* https://leetcode.com/problems/total-hamming-distance/
4+
* Difficulty: Medium
5+
*
6+
* The Hamming distance between two integers is the number of positions at which the
7+
* corresponding bits are different.
8+
*
9+
* Given an integer array nums, return the sum of Hamming distances between all the
10+
* pairs of the integers in nums.
11+
*/
12+
13+
/**
14+
* @param {number[]} nums
15+
* @return {number}
16+
*/
17+
var totalHammingDistance = function(nums) {
18+
let result = 0;
19+
20+
for (let bit = 0; bit < 32; bit++) {
21+
const ones = nums.reduce((count, n) => count + ((n >> bit) & 1), 0);
22+
result += ones * (nums.length - ones);
23+
}
24+
25+
return result;
26+
};

0 commit comments

Comments
 (0)