181. 将整数A转换为B

思路

如果要将整数A转换为B,需要改变多少个bit位?Both n and m are 32-bit integers.
如把31转换为14,需要改变2bit位。
(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))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值