aboutsummaryrefslogtreecommitdiff
path: root/hamming_distance.py
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-09-27 20:37:04 -0600
committerJack Sangdahl <[email protected]>2025-09-27 20:37:04 -0600
commit60f3439c8377ef8b99b5055b471840d53ab200a0 (patch)
tree1a8cc728f7932c3cc3f3debac5b180b1a7bef42e /hamming_distance.py
parent48f4961febc7d03056cd826682e4b3277c7b20ca (diff)
downloadleetcode-60f3439c8377ef8b99b5055b471840d53ab200a0.tar.gz
leetcode-60f3439c8377ef8b99b5055b471840d53ab200a0.zip
461. hamming distance
Diffstat (limited to 'hamming_distance.py')
-rw-r--r--hamming_distance.py27
1 files changed, 27 insertions, 0 deletions
diff --git a/hamming_distance.py b/hamming_distance.py
new file mode 100644
index 0000000..715b35a
--- /dev/null
+++ b/hamming_distance.py
@@ -0,0 +1,27 @@
+# 461. Hamming Distance
+
+"""
+the hamming distance between two integers is the number of positions at which
+the corresponding bits are different. given two integers 'x' and 'y', return
+the hamming distance between them.
+"""
+
+
+class Solution(object):
+ def hammingDistance(self, x, y):
+ """
+ :type x: int
+ :type y: int
+ :rtype: int
+ """
+ ans, n = 0, x ^ y
+ while n:
+ ans += 1
+ n &= n - 1
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.hammingDistance(1, 4))
+ print(obj.hammingDistance(3, 1))