-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhammingDistance.go
More file actions
51 lines (42 loc) · 1.13 KB
/
Copy pathhammingDistance.go
File metadata and controls
51 lines (42 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* https://leetcode.com/problems/hamming-distance/#/description
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 < 2^31.
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.
在信息论中,两个等长字符串之间的汉明距离(英语:Hamming distance)是两个字符串对应位置的不同字符的个数。
换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。
*/
package lbm
func hammingDistance(x int, y int) int {
res := x ^ y
cnt := 0
for res > 0 {
res &= res - 1
cnt++
}
return cnt
}
/*
func hammingDistance(x int, y int) int {
xl, yl := make([]int, 32, 32), make([]int, 32, 32)
for i := 0; x > 0 || y > 0; i++ {
xl[i], yl[i] = x%2, y%2
x, y = x>>1, y>>1
}
r := 0
for i := 0; i < 32; i++ {
if xl[i] != yl[i] {
r++
}
}
return r
}
*/