alex.l alex.l - 2 months ago 15
Python Question

Sum of Two Integers without using '+' operator in python 2 or 3

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


But when one of a, b < 0 or both, how the script should be like?

Answer

+ operator internally makes a call to __add__(). So, you may directly call a.__add__(b) to get sum. Below is the modified code:

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

OR, you may use operator.add(a, b) as:

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