Python solution using zip_longest()


  • 2
    S
    from itertools import izip_longest
    class Solution(object):
        def addStrings(self, num1, num2):
            res, c = "", 0
            for (x, y) in izip_longest(num1[::-1], num2[::-1], fillvalue='0'):
                s = (int(x) + int(y) + c)
                d, c = s % 10, int(s / 10)
                res = str(d) + res
            
            if c > 0: res = str(c) + res
    
            return res

  • 0
    A

    Is this a valid solution? You are using int on the digit, does this violate stipulation #4?


  • 0
    H

    @alvinthai int() is used to map from single char to digit so I think that's fine. You can also substract something to get same result.


  • 0
    Q

    Very pythonic! I had to read up on izip_longest .. Here is my solution, idea is the same just using while loop.

    class Solution(object):
        def addStrings(self, num1, num2):
            res, carry, digit = "", 0, 0
            num1 = list(num1)
            num2 = list(num2)
            while num1 or num2 or carry:
                x, y = 0, 0
                if num1:
                    x = int(num1[-1])
                    num1.pop()
                if num2:
                    y = int(num2[-1])
                    num2.pop()
                carry, digit = (x + y + carry) / 10, (x + y + carry) % 10
                res = str(digit) + res
            return res
    

Log in to reply
 

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