-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathcount_flips_to_convert.py
More file actions
39 lines (30 loc) · 938 Bytes
/
count_flips_to_convert.py
File metadata and controls
39 lines (30 loc) · 938 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
"""
Count Flips to Convert
Determine the minimal number of bits you would need to flip to convert
integer A to integer B. Uses XOR to find differing bits and Brian
Kernighan's algorithm to count them.
Reference: https://en.wikipedia.org/wiki/Hamming_distance
Complexity:
Time: O(k) where k is the number of differing bits
Space: O(1)
"""
from __future__ import annotations
def count_flips_to_convert(first: int, second: int) -> int:
"""Count the number of bit flips needed to convert one integer to another.
Args:
first: The source integer.
second: The target integer.
Returns:
The number of bits that differ between *first* and *second*.
Examples:
>>> count_flips_to_convert(29, 15)
2
>>> count_flips_to_convert(34, 34)
0
"""
diff = first ^ second
count = 0
while diff:
diff &= diff - 1
count += 1
return count