Python solution, simple step by step

  • 0

    My thoughts are as followed.
    First I have to make sure that the length of the strings are equal, which is why I turned both strings into lists and inserted "0" at the front to make them the same size and to simulate the addition in mathematics.
    Then simulating how we do addition in mathematics, we start with adding up from the digit in ones using "(ord(num1.pop()) + ord(num2.pop()))%48."
    To simulate different digit, simply times 10 to the i th power, then add them up.
    In the end, use str() to turn the integer back to string.

    def addStrings(self, num1, num2):
        num1 = list(num1)
        num2 = list(num2)
        if len(num1) < len(num2):
            for i in range(len(num2) - len(num1)):
        elif len(num1) > len(num2):
            for i in range(len(num1) - len(num2)):
        ans = 0 
        for i in range(len(num1)):
            precalculated = (ord(num1.pop()) + ord(num2.pop()))%48
            ans += precalculated * 10**i
        return str(ans)

Log in to reply

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