加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[Swift]LeetCode461. 汉明距离 | Hamming Distance

发布时间:2020-12-14 05:05:08 所属栏目:百科 来源:网络整理
导读: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 = 4Output:

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,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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读