Multiply Strings
Question
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Tags
- Maths
- String
Thought
Reference: https://discuss.leetcode.com/topic/20883/simple-python-solution-18-lines/3
Use the list to store the product between the digits of two numbers.
Code
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
res = [0 for _ in xrange(len(num1) + len(num2))]
for i, digit1 in enumerate(reversed(num1)):
for j, digit2 in enumerate(reversed(num2)):
res[i + j] += int(digit1) * int(digit2)
res[i + j + 1] += res[i + j] / 10
res[i + j] %= 10
while len(res) > 1 and res[-1] == 0:
res.pop()
return ''.join(map(str, reversed(res)))