Python: 7-line & 52ms (+ 1-liner for fun)


  • 7
    def addStrings(self, num1, num2):
        z = itertools.izip_longest(num1[::-1], num2[::-1], fillvalue='0')
        res, carry, zero2 = [], 0, 2*ord('0')
        for i in z:
            cur_sum = ord(i[0]) + ord(i[1]) - zero2 + carry
            res.append(str(cur_sum % 10))
            carry = cur_sum // 10
        return ('1' if carry else '') + ''.join(res[::-1])
    

    The above I think would be the expected answer in an interview. But just for fun based on a similar idea we can have a (rather long :-) one-liner. It technically satisfies the problem conditions, although it may warrant disqualification from the contest, depending on interpretation:

    • "You must not use any built-in BigInteger library" -> I don't use a library; I am just making use of the fact that Python's standard int supports arbitrarily large integers.
    • "or convert the inputs to integer directly" -> I don't; I sum them digit by digit. It is the result that I convert to integer and back.

    Formated for added clarity, although everything can be put on the same line:

    def addStrings(self, num1, num2):
         return str(
                  reduce(lambda a, b: 10*a + b, 
                     map(lambda x: ord(x[0])+ord(x[1])-2*ord('0'),
                       list(itertools.izip_longest(num1[::-1], num2[::-1], fillvalue='0'))[::-1]
                     ) 
                  )
                )
    

    Would the one liner be acceptable in the contest?


  • 3

    @dalwise said in Python: 7-line & 52ms + legal 1-liner:

    Would the one liner be acceptable in the contest?

    Of course not.

    int clearly is part of the library. And even if it weren't, it's clear how the rule is meant and that you're violating it.


  • 0

    @StefanPochmann Yes, the second solution is certainly a stretch of the rules, but still a fun exercise. I do think that it can be argued that I don't use a BigInteger library: I use the standard int (which surely is allowed, right?). I agree with you that I use it in a way which does violate the intention of the rules (but I think not the rules themselves ;).

    I've changed the title to remove the "legal" part to avoid confusion and I won't argue further on its "legality", since as originally mentioned the one-liner is just for fun. The "normal" answer is the first one.


  • 0
    L

    @dalwise
    Don't really see a point in carrying if you're adding numbers using ord like you do. "Technically" this solution also follows the standards setup by the question

    def convert(c): 
                return ord(c)-ord('0')
            x1=x2=0    
            for i in num1:
                x1=x1*10+ convert(i)
            for j in num2:
                x2=x2*10+convert(j)
            x=x1+x2
            return str(x)

Log in to reply
 

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