-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0043-multiply-strings.py
More file actions
36 lines (26 loc) · 924 Bytes
/
0043-multiply-strings.py
File metadata and controls
36 lines (26 loc) · 924 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# time complexity: O(m*n)
# space complexity: O(m+n)
class Solution:
def multiply(self, num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
N = len(num1) + len(num2)
result = [0] * N
firstNum = num1[::-1]
secondNum = num2[::-1]
for place1, digit1 in enumerate(firstNum):
for place2, digit2 in enumerate(secondNum):
currPos = place1 + place2
carry = result[currPos]
multiplication = int(digit1) * int(digit2) + carry
result[currPos] = multiplication % 10
result[currPos + 1] += multiplication // 10
if result[-1] == 0:
result.pop()
return "".join(str(digit) for digit in result[::-1])
num1 = "2"
num2 = "3"
print(Solution().multiply(num1, num2))
num1 = "123"
num2 = "456"
print(Solution().multiply(num1, num2))