思路
如果要将整数A转换为B,需要改变多少个bit位?Both n and m are 32-bit integers.
如把31转换为14,需要改变2个bit位。
(31)10=(011111)2
(14)10=(001110)2
(67)10=(100011)2
(1)10 =(000001)2
(-1)10=(111111)
分析:
可以转换为 A^B 的二进制 1 的数量
数字的二进制的1的个数可以使用 n & (n -1) 来求
n & (n -1) 的作用是去掉末尾的1
Python
class Solution:
"""
@param: a: An integer
@param: b: An integer
@return: An integer
"""
def bitSwapRequired(self, a, b):
# write your code here
import ctypes
sum_res, target = 0, ctypes.c_int32(a).value ^ ctypes.c_int32(b).value
while target:
sum_res += 1
target = ctypes.c_int32(target).value & ctypes.c_int32(target - 1).value
return sum_res
a, b = 1, -1
s = Solution()
print(s.bitSwapRequired(a, b))