★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-yjjtngvn-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.git
Now your job is to find the total Hamming distance between all pairs of the given numbers.github
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:微信
0
to 10^9
10^4
.兩個整數的 漢明距離 指的是這兩個數字的二進制數對應位不一樣的數量。this
計算一個數組中,任意兩個數之間漢明距離的總和。spa
示例:code
輸入: 4, 14, 2 輸出: 6 解釋: 在二進制表示中,4表示爲0100,14表示爲1110,2表示爲0010。(這樣表示是爲了體現後四位之間關係) 因此答案爲: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.
注意:htm
0
到 10^9
。10^4
。1 class Solution { 2 func totalHammingDistance(_ nums: [Int]) -> Int { 3 var res:Int = 0 4 var n:Int = nums.count 5 for i in 0..<32 6 { 7 var cnt:Int = 0 8 for num in nums 9 { 10 if num & (1 << i) != 0 11 { 12 cnt += 1 13 } 14 } 15 res += cnt * (n - cnt) 16 } 17 return res 18 } 19 }