在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 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:
两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。 计算一个数组中,任意两个数之间汉明距离的总和。 示例: 输入: 4, 14, 2 输出: 6 解释: 在二进制表示中,4表示为0100,14表示为1110,2表示为0010。(这样表示是为了体现后四位之间关系) 所以答案为: HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6. 注意:
Runtime: 668 ms
Memory Usage: 8.1 MB
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 }
|
请发表评论