Python solution


  • 0
    R
    class Solution:
        def int2(self, digit):
            return ord(digit) - ord('0')
    
        def chr2(self, digit):
            return chr(ord('0') + digit)
        
        def addStrings(self, num1, num2):
            """
            :type num1: str
            :type num2: str
            :rtype: str
            """        
            count1 = len(num1) - 1
            count2 = len(num2) - 1
            carry = 0
            total_sum = ""
            
            while count1 >= 0 or count2 >= 0:
                first_num = self.int2(num1[count1]) if count1 >= 0 else 0
                second_num = self.int2(num2[count2]) if count2 >= 0 else 0
                digit_sum = first_num + second_num + carry
                total_sum = self.chr2(digit_sum%10) + total_sum
                carry = int(digit_sum/10)
                
                count1 -= 1
                count2 -= 1
                
                # This is for the case when one of the numbers is shorter
                # and carry leftover is 0. e.g. 123 + 999999456
                if carry == 0:
                    if count1 < 0  and count2 > 0:
                        return num2[:count2+1] + total_sum
                    if count1 > 0 and count2 < 0:
                        return num1[:count1+1] + total_sum
    
            if carry > 0:
                return str(carry) + total_sum
            return total_sum
    

Log in to reply
 

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