This question already has an answer here:
Is it possible to write a function adding two integers without control flow and strictly bitwise operations?
                                
                                    (1个答案)
                                
                        
                                2年前关闭。
            
                    
我的问题是,如何在不使用布尔运算符,if-else条件运算符或逻辑运算符的情况下相加两个数字?

我一直在尝试编写一个在Python中将两个数字相加的代码,但只能使用按位运算符。换句话说,没有循环,if-else和算术运算符。

我也在此页面和其他编程站点中进行了搜索,但是针对此问题的所有解决方案都具有while循环或if-else条件。我找到了一个可能的解决方案,
假定它是递归执行的,但是却产生了递归错误:最大递归深度超过了。因为它没有基本情况

现在我问自己,是否可以这样做。然后另一个问题是,可能吗?如果是的话,我该怎么办?

这是我失败的代码:

x=7
y=2
def Sum(x, y):
    suma=x^y
    carry=(x&y)<<1
    return Sum(suma, carry)
print(Sum(x, y))

最佳答案

您在评论中说输入必须不大于10 ^ 5。在这种情况下,有限数量的进位传播步骤足以消除进位项并产生最终和:

def binop_add(x, y):
    sum, carry = x, y
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 1
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 2
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 3
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 4
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 5
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 6
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 7
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 8
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 9
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 10
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 11
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 12
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 13
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 14
    sum, carry = (sum ^ carry), (sum & carry) << 1 # 15
    # assert carry == 0
    return sum


每轮sum, carry = (sum ^ carry), (sum & carry) << 1保留sum + carry == x + y的不变式。每一轮之后,carry必须以至少一个0位结束。

15回合后,carry必须以至少15个零位结尾。要使carry在此时不为零,carry必须至少为1 << 15,即32768,比可能的高。此时,carry必须为0,所以sum + carry == sum == x + y,我们返回sum

关于python - 只有两个按位运算符的总数是两个? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52339523/

10-09 13:22