Concise 5-liner in Python

  • 0

    Pad the strings with ‘0’ so both strings have the same length. I saw @StefanPochmann used ’0’*-diff elsewhere, so it’s to his credit.

    In the end, append carry to the list and use lstrip to remove the ‘0’s.

    class Solution(object):
        def addStrings(self, num1, num2):
            diff, carry, ret = len(num2)-len(num1), 0, []
            for c1,c2 in zip(num1[::-1]+'0'*diff, num2[::-1]+'0'*-diff):
                carry, n = divmod(carry+ord(c1)+ord(c2)-ord('0')*2, 10)
            return ''.join([str(carry)]+ret[::-1]).lstrip('0') or '0'

  • 0

    You could also use itertools.izip_longest, overall it's a bit shorter.

  • 1

    @StefanPochmann Actually I know this, but never managed to remember it. Don't think i can remember it for interviews, either :P

Log in to reply

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