我想知道这个while循环会执行多少次。此函数使用XOR和AND将两个数字相加。
def Add(x, y):
# Iterate till there is no carry
while (y != 0):
# carry now contains common
# set bits of x and y
carry = x & y
# Sum of bits of x and y where at
# least one of the bits is not set
x = x ^ y
# Carry is shifted by one so that
# adding it to x gives the required sum
y = carry << 1
return x
``
关于while循环执行了多少次没有固定答案。当从一个位置到另一个位置有一个进位位时,总是执行while循环。因此,您需要知道数字在二进制中到底是什么样子。但是您可以肯定地说的是最大可能执行的次数。它是较大数字的长度,为位+1。为什么?因为如果那是最大数,则可以进行一次进位。让我们以add(1,7)= 8(001 + 111 = 1000)为例。从第一位开始的进位传递两个第二位置,然后传递到第三位置,然后传递到第四位置。 4次迭代,这等于7的长度,并且+ 1 = 4。
如果x AND y = 0,答案似乎为1,否则为1 + x + y的二进制表示形式中的零数。