Skip to content

Instantly share code, notes, and snippets.

@farkwun
Created September 16, 2017 07:12
Show Gist options
  • Save farkwun/05fe4fbe29c9a5e461f2144d62b748e7 to your computer and use it in GitHub Desktop.
Save farkwun/05fe4fbe29c9a5e461f2144d62b748e7 to your computer and use it in GitHub Desktop.
43. Multiply Strings
# https://leetcode.com/problems/multiply-strings/description/
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
temp_values = []
num1 = num1[::-1]
num2 = num2[::-1]
for n1 in num1:
carry = 0
temp = ['0'] * len(temp_values)
a = int(n1)
for n2 in num2:
b = int(n2)
c = (a * b) + carry
temp.append(str(c % 10))
carry = c // 10
if carry != 0:
temp.append(str(carry))
temp_values.append(''.join(temp))
total = ""
for v in temp_values:
total = add_rev_num_strs(total, v)
total = total[::-1]
for digit in total:
if digit != '0':
return total
return '0'
def add_rev_num_strs(a, b):
a_ptr = b_ptr = 0
carry = 0
result = []
while a_ptr < len(a) or b_ptr < len(b):
temp_a = 0
temp_b = 0
if a_ptr < len(a):
temp_a = int(a[a_ptr])
if b_ptr < len(b):
temp_b = int(b[b_ptr])
temp = temp_a + temp_b + carry
result.append(str(temp % 10))
carry = temp // 10
a_ptr += 1
b_ptr += 1
if carry != 0:
result.append(str(carry))
return ''.join(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment