gpt4 book ai didi

python - 在 python 2 或 3 中不使用 '+' 运算符的两个整数之和

转载 作者:行者123 更新时间:2023-11-30 22:49:43 24 4
gpt4 key购买 nike

class Solution(object):
def getSum(self, a, b):
if (a == 0):
return b
if (b == 0):
return a;
while(b != 0):
_a = a ^ b
_b = (a & b) << 1
a = _a
b = _b
return a

但是当 a、b < 0 或两者之一时,脚本应该是什么样子?

最佳答案

+ 运算符在内部调用 __add__()。因此,您可以直接调用a.__add__(b)来获取总和。下面是修改后的代码:

>>> class Solution(object):
... def getSum(self, a, b):
... return a.__add__(b)
...
>>> s = Solution()
>>> s.getSum(1, 2)
3

或者,您可以使用operator.add(a, b)如:

>>> import operator
>>> operator.add(1, 2)
3

关于python - 在 python 2 或 3 中不使用 '+' 运算符的两个整数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39646749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com