A Python solution


  • 3
    C

    For python the add function only works when

    • a*b>=0 , or
    • a < 0 and abs(a) > b > 0 (the negative number has a larger absolute value)
    • b < 0 and abs(b) > a > 0

    Modify it accordingly (use add(~n, 1) to turn n into -n):

    def getSum(self, a, b):
        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 
    

    If we are allowed to use -n:

    def getSum(self, a, b):
        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 -a == b:
                return 0
            if -a < b:
                return -add(-a, -b)
    
        return add(a, b)

  • 0

    Are we allowed to use negate "-"?


  • 0
    C

    @bayesric Added a modified solution without it!


  • 0
    C

    @cmc why add() works only in those conditions?


  • 0

    @catbaron- that is not true, it always work.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.