From 60f3439c8377ef8b99b5055b471840d53ab200a0 Mon Sep 17 00:00:00 2001 From: Jack Sangdahl Date: Sat, 27 Sep 2025 20:37:04 -0600 Subject: 461. hamming distance --- hamming_distance.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 hamming_distance.py (limited to 'hamming_distance.py') 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)) -- cgit v1.2.3