★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(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 }