477-Total Hamming Distance
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:
- Elements of the given array are in the range of 0 to 10^9
- Length of the array will not exceed 10^4.
問題描述
漢明距離為兩數二進位制表示對應位不同的個數。
現在你需要計算陣列中所有對的漢明距離之和
問題分析
迭代每一位, 對每一位算出漢明距離, 累加
解法
class Solution {
public int totalHammingDistance(int[] nums) {
int total = 0, n = nums.length;
for (int j = 0;j < 32;j++) {
int bitCount = 0;
for (int i = 0;i < n;i++) bitCount += (nums[i] >> j) & 1;
total += bitCount * (n - bitCount);
}
return total;
}
}
相關文章
- LeetCode 461. Hamming DistanceLeetCode
- 漢明距離(Hamming distance)
- Kata:Hamming number
- simhash&hamming distince
- Matrix Distance
- A - Distance in Tree
- [Leetcode] Edit DistanceLeetCode
- 7.47 CLUSTER_DISTANCE
- 海明碼(Hamming Code)的知識點
- POI2012ODL-Distance
- distance(Floyd求最短路)
- 錯誤 1 error LNK2019: 無法解析的外部符號 "public: __thiscall Distance::Distance(int)" (??0Distance@@QAE@H@Z),該符...Error符號
- [LeetCode] 2739. Total Distance TraveledLeetCode
- 【Lintcode】1623. Minimal Distance In The Array
- [LeetCode] 243. Shortest Word DistanceLeetCode
- LeetCode之Shortest Distance to a Character(Kotlin)LeetCodeKotlin
- ABC359 G - Sum of Tree Distance
- [Over-Distance] Ubuntu 24.04 LTS UpdateUbuntu
- 1046 Shortest Distance(簡單模擬)
- [LeetCode] 244. Shortest Word Distance IILeetCode
- [ABC353F] Tile Distance 題解
- [LeetCode] 317. Shortest Distance from All BuildingsLeetCodeUI
- [LeetCode] 1385. Find the Distance Value Between Two ArraysLeetCode
- abc359_G Sum of Tree Distance 題解
- Java解決LeetCode72題 Edit DistanceJavaLeetCode
- LeetCode 1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance??LeetCode
- Codeforces Round 903 (Div. 3) F. Minimum Maximum Distance
- 【leetcode】72. Edit Distance 編輯距離計算LeetCode
- 題解:AT_abc382_d [ABC382D] Keep Distance
- GAN量化評估方法——IS(Inception Score)和FID(Frechet Inception Distance score)
- 相容oracle的edit_distance_similarity 比較兩個字串相似度OracleMILA字串
- 資料對齊-編輯距離演算法詳解(Levenshtein distance)演算法
- P9058 [Ynoi2004] rpmtdq 與 P9678 [ICPC2022 Jinan R] Tree DistanceNaN
- 行人重識別(17)——程式碼實踐之區域性對齊最小距離演算法(local_distance.py)演算法