Using bit operation in Python3. The algorithm has already been accepted.


  • 0
    N

    This method is using bit operation to get sum of 2 integers. i write 2 addional functions add and spe. Add() is normal bit operation for add calculation. Spe() is for the follow special situation. if the positive integer bigger than the absolute value of negative integer when one is positive and another one is negative, there is something go wrong. So i use 2's complement to convert these two integers for going correction. Note that when you wanna using complement, don't forget plus one after complement operation.

    class Solution:
        def add(a,b):
            while(b != 0):
                carry = a&b
                a = a^b
                b = carry << 1
            return a
        def spe(a,b):
            a = ~a
            a += 1
            b = ~b
            b += 1
            while(b != 0):
                carry = a&b
                a = a^b
                b = carry << 1
            a = ~a
            a += 1
            return a
        def getSum(self, a, b):
            """
            :type a: int
            :type b: int
            :rtype: int
            """
            if (a >= 0 and b < 0) or (a < 0 and b >= 0):
                if a == abs(b) or abs(a) == b:
                    return 0
                if a >= 0 and a > abs(b):
                    return Solution.spe(a,b)
                if b >= 0 and b > abs(a):
                    return Solution.spe(b,a)
                return Solution.add(a,b)
            else:
                return Solution.add(a,b)
                    
    

Log in to reply
 

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