[Swift]LeetCode461. 汉明距离 | Hamming Distance
作者:互联网
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
, calculate the Hamming distance.
Note:
0 ≤ x
, y
< 231.
Example:
Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.
两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x
和 y
,计算它们之间的汉明距离。
注意:
0 ≤ x
, y
< 231.
示例:
输入: x = 1, y = 4 输出: 2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭头指出了对应二进制位不同的位置。
8ms
1 class Solution { 2 func hammingDistance(_ x: Int, _ y: Int) -> Int { 3 return (x^y).nonzeroBitCount 4 } 5 }
8ms
1 class Solution { 2 func hammingDistance(_ x: Int, _ y: Int) -> Int { 3 if (x ^ y) == 0 {return 0} 4 return (x ^ y) % 2 + hammingDistance(x / 2, y / 2) 5 } 6 }
8ms
1 class Solution { 2 func hammingDistance(_ x: Int, _ y: Int) -> Int { 3 return String(x ^ y, radix: 2).replacingOccurrences(of: "0", with: "").count 4 } 5 }
8ms
1 class Solution { 2 func hammingDistance(_ x: Int, _ y: Int) -> Int { 3 var r = x ^ y 4 // 这个就是计算位数为1的方法 5 var count = 0 6 while r != 0 { 7 r = r & (r - 1) 8 count += 1 9 } 10 return count 11 } 12 }
12ms
1 class Solution { 2 func hammingDistance(_ x: Int, _ y: Int) -> Int { 3 var numX = min(x, y) 4 var numY = max(x, y) 5 var result = 0 6 while numY > 0 { 7 if (numX % 2 != numY % 2) { 8 result += 1 9 } 10 numX = numX / 2 11 numY = numY / 2 12 } 13 return result 14 } 15 }
12ms
1 class Solution { 2 func pad(string : String, toSize: Int) -> String { 3 var padded = string 4 for _ in 0..<(toSize - string.characters.count) { 5 padded = "0" + padded 6 } 7 return padded 8 } 9 10 func hammingDistance(_ x: Int, _ y: Int) -> Int { 11 guard x >= 0 && y < 4294967296 else { 12 return 0 13 } 14 var a = pad(string: String(x, radix: 2, uppercase: false), toSize: 32) 15 var b = pad(string: String(y, radix: 2, uppercase: false), toSize: 32) 16 var res = 0 17 for i in 0..<32 { 18 if a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] { 19 res += 1 20 } 21 } 22 return res 23 } 24 }
标签:Distance,return,func,Int,hammingDistance,Solution,Hamming,汉明,var 来源: https://www.cnblogs.com/strengthen/p/10343541.html