【位运算-简单】面试题 05.06. 整数转换

【题目】
整数转换。编写一个函数,确定需要改变几个位才能将整数A转成整数B。
【示例1】
输入:A = 29 (或者0b11101), B = 15(或者0b01111)
输出:2
【示例2】
输入:A = 1,B = 2
输出:2
【提示】
A,B范围在[-2147483648, 2147483647]之间
【代码】
【Python】
在这里插入图片描述

class Solution:
    def convertInteger(self, A: int, B: int) -> int:
        cnt=0
        for i in range(32):
            if A&1!=B&1:
                cnt+=1
            A>>=1
            B>>=1
        return cnt

猜你喜欢

转载自blog.csdn.net/kz_java/article/details/115122563