Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created December 7, 2020 19:06
Show Gist options
  • Save les-peters/6e8ca834fdc4f02dcfc43389e91fc352 to your computer and use it in GitHub Desktop.
Save les-peters/6e8ca834fdc4f02dcfc43389e91fc352 to your computer and use it in GitHub Desktop.
String Multiply without Multiplying
import re
from itertools import cycle, islice
question = """
Given two non-negative integers n1 and n2 represented as strings,
return the product of n1 and n2, also represented as a string.
Neither input will start with 0, and don’t just convert it to an
integer and do the math that way.
Examples:
$ stringMultiply(“123”, “456”)
$ “56088”
"""
def stringMultiple(a, b):
a1 = [char for char in a]
b1 = [char for char in b]
c = [[ 0 for x in range(0, len(a1))] for y in range(0, len(b1))]
w = [[] for x in range(0, len(a1) + len(b1))]
for a2 in range(0, len(a1)):
for b2 in range(0, len(b1)):
cprod = str(eval('+'.join(islice(cycle(a1[a2]), (ord(b1[b2])-48)))))
cprod = '0' + cprod if len(cprod) == 1 else cprod
c[a2][b2] = cprod
c2 = a2 + b2 + 1
w[c2].append([a2,b2])
carry = 0
w1 = [ [] for x in range(0, len(w)) ]
for w2 in reversed(range(0,len(w))):
w3 = 0
if w2 == len(w) - 1:
for w4 in w[w2]:
a3, b3 = w4
w1[w2] = [char for char in c[a3][b3]][1]
carry = '0'
else:
w5 = []
for w4 in w[w2]:
a3, b3 = w4
w1[w2].append([char for char in c[a3][b3]][1])
for w5 in w[w2 + 1]:
a3, b3 = w5
w1[w2].append([char for char in c[a3][b3]][0])
w1[w2].append(carry)
w6 = str(eval('+'.join(w1[w2])))
w6 = '0' + w6 if len(w6) == 1 else w6
carry = [char for char in w6][0]
y = [char for char in w6][1]
w1[w2] = y
wz = re.sub(r'^0', '', ''.join(w1))
return wz
print(stringMultiple("123", "456"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment