"如何不使用^操作实现异或运算"(python)

分析与解答:最简单的方法就是遍历两个整数所有的位,如果两个数的某一位相等,那么结果中这一位的值为0,否则结果中这一位的值为1。

class MyXOR:
    def __init__(self):
        self.BITS = 32

    # 获取x与y的异或的结果
    def xor(self, x, y):
        res = 0
        i = self.BITS - 1
        while i >= 0:
            # 获取x与y当前的bit值
            b1 = (x & (1 << i)) > 0
            b2 = (y & (1 << i)) > 0

            # 只有这两个都是1或0的时候结果为0
            if (b1 == b2):
                xoredBit = 0
            else:
                xoredBit = 1

            res <<= 1
            res |= xoredBit
            i -= 1

        return res

if __name__ == "__main__":
    x = 3
    y = 5
    mx = MyXOR()
    print(mx.xor(x, y))

猜你喜欢

转载自blog.csdn.net/qq_42013574/article/details/89029783