3226. 使两个整数相等的位更改次数
为保证权益,题目请参考 3226. 使两个整数相等的位更改次数(From LeetCode).
解决方案1
Python
python
class Solution:
def minChanges(self, n: int, k: int) -> int:
ans = 0
while n != k:
l = n % 2
r = k % 2
if l != r:
if l == 1 and r == 0:
ans += 1
else:
return -1
n = n // 2
k = k // 2
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
解决方案2
Python
python
class Solution:
def minChanges(self, n: int, k: int) -> int:
return (n ^ k).bit_count() if (n & k == k) else -1
1
2
3
2
3