Skip to content

Commit

Permalink
Create 371-Sum-of-Two-Integers.py
Browse files Browse the repository at this point in the history
  • Loading branch information
neetcode-gh authored Dec 26, 2021
1 parent 7ca9c48 commit 99805d2
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions 371-Sum-of-Two-Integers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution:
def getSum(self, a: int, b: int) -> int:
def add(a, b):
if not a or not b:
return a or b
return add(a^b, (a&b) << 1)

if a*b < 0: # assume a < 0, b > 0
if a > 0:
return self.getSum(b, a)
if add(~a, 1) == b: # -a == b
return 0
if add(~a, 1) < b: # -a < b
return add(~add(add(~a, 1), add(~b, 1)),1) # -add(-a, -b)

return add(a, b) # a*b >= 0 or (-a) > b > 0

0 comments on commit 99805d2

Please sign in to comment.