Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example:
Given a = 1 and b = 2, return 3.
class Solution(object):
def getSum(self, a, b):
"""
:type a: int
:type b: int
:rtype: int
"""
if b == 0:
return a
if a == 0:
return b
c = a ^ b
d = 0xFFFFFFFF &((a&b) << 1)
if d > 0x7FFFFFFF:
s = -(~(d - 1) & 0xFFFFFFFF)
else:
s = d
return Solution().getSum(c,s)
http://www.cnblogs.com/zhengyun_ustc/archive/2009/10/14/shifting.html
http://stackoverflow.com/questions/7201207/python-bitshift-32-bit-constraint