★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-wubfpgln-kh.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.git
Given two integers x
and y
, calculate the Hamming distance.github
Note:
0 ≤ x
, y
< 231.微信
Example:spa
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.
兩個整數之間的漢明距離指的是這兩個數字對應二進制位不一樣的位置的數目。code
給出兩個整數 x
和 y
,計算它們之間的漢明距離。htm
注意:
0 ≤ x
, y
< 231.blog
示例:ip
輸入: 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 }
8msci
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 }