9-line Python solution, two layer for-loop, iterate each digit of multiplier


  • 0
    K
    def multiply(self, num1, num2):
        if num1 == '0' or num2 == '0': return '0'
        a, b, len_a, len_b = [ord(i) - 48 for i in num1[::-1]], [ord(j) - 48 for j in num2[::-1]], len(num1), len(num2)
        res = [0] * (len_a + len_b)
        for i in xrange(len_a):
            for j in xrange(len_b):
                res[i + j] += a[i] * b[j]
                res[i + j + 1] += res[i + j] / 10
                res[i + j] %= 10
        return ''.join([chr(48 + x) for x in res])[::-1].lstrip('0')

  • 0

    How is that "one digit at a time"?


  • 0
    K

    It's for multiplier, not for product. I've modified the title.


  • 0

    Ah, I guess you say it to distinguish it from solutions which simply use Pythons arbitrarily larger ints? I did the latter and wrote myself the note "TODO: Do it on your own? Maybe in another language, where it makes sense?" :-D

    Which I then did here, doing it one result digit at a time, but in C++. I imagine it could still look good in Python using sum, but meh... still doesn't make much sense.


  • 0
    K

    Yeah, this problem is intended for C++ or Java where int has fixed bits. I also saw MAX_INT 2147483647 restriction on problem 8 and problem 29, but in Python ints are automatically promoted to long when sys.maxint + 1 occurs.


Log in to reply
 

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