One positive and one negative case is successful for python. a,b=-1,1 is ok by rules.

  • 0
    class Solution(object):
        def getSum(self, a, b):
            def add(a,b):
                ans = 0
                while b:
                    ans = a^b
                    b   = (a&b)<<1
                    a   = ans
                return ans
            def sub(a,b):
                temp = add(1,~b)
                return add(a, temp)
            #print ~1,~0,~(-1),~(-2),~(-3),~(-4),~(-5),~(-6),~(-7),~(-8)
            #1.sub(8, (-3))  is ok,    a,b=8,3
            #2.sub(-8, (-3)) is ok,    a,b=-8,3,value=a+b=-5
            #3.sub(-8, 3)    is ok,    a,b=-8,-3,value=a+b=-11
            #4.sub(8, 3)     is error, a,b=8,-3,value=a+b=5,but failed, I made a=-8,b=3,because of step2.get -sub(-a, b) as results.
            #5.sub(-3, -8)   is error
            if a>=0 and b>=0:
                return add(a, b)
            elif a<0 and b>=0:
                if -a > b:
                    return sub(a, -b)
                    return -sub(-b, a)
            elif a>=0 and b<=0:
                if a < -b:
                    return sub(b, -a)
                    return -sub(-a ,b)
                if a>b:
                    return sub(b,-a)
                    return sub(a,-b)
    a = Solution()
    numa, numb = 5,17
    #numa, numb = 3,-8
    #numa, numb = -3,-8
    #numa, numb = -8,3
    #numa, numb = -3,8
    #numa, numb = 3,-8
    #numa, numb = 8,-3
    #numa, numb = -8,-3
    #numa, numb = -3,-8
    numa, numb  = -1, 1
    print a.getSum(numa, numb)

    I don't like rules. But it is useful. Could you have more good?

  • 2
    import ctypes
    class Solution(object):
        def getSum(self, a, b):
            sum = 0
            carry = ctypes.c_int32(b)
            while carry.value != 0:
                sum = a ^ carry.value
                carry = ctypes.c_int32(a & carry.value)
                carry.value <<= 1
                a = sum
            return sum

  • 0

    Could you explain the difference between Python int and ctypes.c_int32?

  • 2

    @mgchbot python int will be long and long, without bit limit?. But you can get the maxint by import sys;print sys.maxint; ctypes.c_int32 make sure that it is 32 bit for programming.

Log in to reply

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