Skip to content

Commit c8f5c29

Browse files
authored
Create hamming_distance.py
1 parent 4d1c6c4 commit c8f5c29

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

hamming_distance.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
"""
3+
@param x: an integer
4+
@param y: an integer
5+
@return: return an integer, denote the Hamming Distance between two integers
6+
"""
7+
def hammingDistance(self, x, y):
8+
# write your code here
9+
# 转成2进制字符串后比较,记得长度不同前面补0。
10+
r = 0
11+
bx = bin(x)[2:]
12+
by = bin(y)[2:]
13+
diff = abs(len(bx) - len(by))
14+
if len(bx) > len(by):
15+
by = '0' * diff + by
16+
else:
17+
bx = '0' * diff + bx
18+
for i in range(len(bx)):
19+
if bx[i] != by[i]:
20+
r += 1
21+
return r
22+
23+
# easy: https://www.lintcode.com/problem/hamming-distance

0 commit comments

Comments
 (0)