Skip to content

Commit 9e44778

Browse files
authored
Create hamming-distance.py
1 parent f9d8dae commit 9e44778

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Python/hamming-distance.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(1)
2+
# Space: O(1)
3+
4+
# The Hamming distance between two integers is the number of positions
5+
# at which the corresponding bits are different.
6+
#
7+
# Given two integers x and y, calculate the Hamming distance.
8+
#
9+
# Note:
10+
# 0 ≤ x, y < 231.
11+
#
12+
# Example:
13+
#
14+
# Input: x = 1, y = 4
15+
#
16+
# Output: 2
17+
#
18+
# Explanation:
19+
# 1 (0 0 0 1)
20+
# 4 (0 1 0 0)
21+
# ↑ ↑
22+
#
23+
# The above arrows point to positions where the corresponding bits are different.
24+
25+
class Solution(object):
26+
def hammingDistance(self, x, y):
27+
"""
28+
:type x: int
29+
:type y: int
30+
:rtype: int
31+
"""
32+
distance = 0
33+
z = x^y
34+
while z:
35+
distance += 1
36+
z &= z-1
37+
return distance

0 commit comments

Comments
 (0)