【发布时间】:2019-12-07 08:44:20
【问题描述】:
我想知道这个 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
``
【问题讨论】:
-
添加一个计数器,在循环前初始化,循环内加1,与x一起打印/返回值?你的问题在哪里?
-
他想知道它根据输入执行了多少次。
-
def Add(x, y): counter = 0 # 迭代直到没有进位 while (y != 0): counter +=1 # carry now contains common # set bits of x and y进位 = x & y # x 和 y 的位总和,其中至少有一个位未设置 x = x ^ y # 进位移位 1,以便 # 将其添加到 x 得到所需的总和 y = carry
-
如果我们有这样的值:y=100010 和 x = 0,那么根据你的说法应该有 0 次迭代,但只有一次迭代。
标签: python time-complexity bit-manipulation bitwise-operators addition