Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Tags: Binary
Try It!
Discussion
Video
Solution
class Solution:
def getSum(self, a: int, b: int) -> int:
mask = 0xffffffff
while b & mask != 0:
carry = a & b
a ^= b
b = carry << 1
# if our answer was negative b/carry would keep on being shifted outside of 32 bits
if b == 0:
return a
else:
return a & mask