-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path461_hamming_distance.py
More file actions
26 lines (18 loc) · 640 Bytes
/
461_hamming_distance.py
File metadata and controls
26 lines (18 loc) · 640 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import unittest
class Solution:
"""
This solution does a bitwise XOR between the two numbers to
create a number with the differing bits. Then the algorithm
keeps checking the rightmost bit while shifting the resulting
number to the right until the number eventually is equal to zero.
"""
def hammingDistance(self, x: int, y: int) -> int:
bits = 0
xor = x ^ y
while xor:
bits += xor & 1
xor = xor >> 1
return bits
class TestSolution(unittest.TestCase):
def test_first_example(self):
self.assertEqual(Solution().hammingDistance(1, 4), 2)