[Swift]LeetCode461. 汉明距离 | Hamming Distance
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10343541.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了