Python Solution 99.93%


  • 0
    C

    class Solution(object):

    def halfAdder(self,a,b): #implement the half adder
        s = a^b
        co = a&b
        return s, co
    
    def fullAdder(self,a,b,ci): #implement the full adder
        (s,co1) = self.halfAdder(a,b)
        (s,co2) = self.halfAdder(ci,s)
    
        co = co1|co2
        return s, co
        
    def getSum(self, a, b):
        
        mask = 1
        ci = 0
        sum1 = 0
    
        while mask <= 0x080000000:
    
            a1 = a&mask
            b1 = b&mask
            (s,ci) = self.fullAdder(a1,b1,ci)
            sum1=sum1|s
            ci = ci << 1
            mask = mask<<1
        
        MAX = 0x7FFFFFFF
        mask = 0xFFFFFFFF
    
        if sum1 > MAX: #If the final sum is negative, get the two complement number of the sum
            sum1 = ~(sum1 ^ mask)
    
        return sum1

Log in to reply
 

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