43. Multiply Strings
https://leetcode.com/problems/multiply-strings
Python
Use enumerate index as pos
class Solution:
def multiply(self, num1: str, num2: str) -> str:
result = 0
for pos1, char1 in enumerate(num1[::-1]):
for pos2, char2 in enumerate(num2[::-1]):
result += int(char1) * int(char2) * (10**(pos1+pos2))
return str(result)
Self-calculate power
(Second try, not that better solution)
class Solution:
def multiply(self, num1: str, num2: str) -> str:
ans = 0
power = 0
for ns1 in num1[::-1]:
level_total = 0
level_pwr = 0
for ns2 in num2[::-1]:
n1 = ord(ns1) - ord('0')
n2 = ord(ns2) - ord('0')
mult = n1 * n2
level_total += mult * (10**level_pwr)
level_pwr += 1
ans += level_total*(10**power)
power += 1
return str(ans)