面试题 05.06. 整数转换

面试题 05.06. 整数转换
整数转换。编写一个函数,确定需要改变几个位才能将整数A转成整数B。

示例1:

输入:A = 29 (或者0b11101), B = 15(或者0b01111)
输出:2
示例2:

输入:A = 1,B = 2
输出:2
提示:

A,B范围在[-2147483648, 2147483647]之间

解题思路

此处撰写解题思路

代码

第一种 使用与

class Solution:
    def convertInteger(self, A: int, B: int) -> int:
        count = 0
        for i in range(32):
            test = 1 << i
            count += 0 if test & A == test & B else 1

        return count

第二种 推荐 使用异或

class Solution:
    def convertInteger(self, A: int, B: int) -> int:
        count = 0
        diff = A ^ B
        for i in range(32):
            count += 1 if 1 << i & diff else 0
        return count

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值