Skip to main content

371. Sum of Two Integers

https://leetcode.com/problems/sum-of-two-integers/

Python

  • Use operator module for better understand
from operator import xor, invert, and_


class Solution:
def getSum(self, a: int, b: int) -> int:
x, y = abs(a), abs(b)

# Ensure x >= y
if x < y:
return self.getSum(b, a)

sign = 1 if a > 0 else -1

if a * b >= 0:
# a and b are possitive integers
while y:
x, y = xor(x, y), and_(x, y) << 1
else:
while y:
x, y = xor(x, y), and_(invert(x), y) << 1

return sign * x

Javascript

var getSum = function(a, b) {
while (b != 0){
const c = a & b;
a = a^b;
b = c << 1;
}
return a;
};