We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent f9d8dae commit 9e44778Copy full SHA for 9e44778
Python/hamming-distance.py
@@ -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