Skip to content

Instantly share code, notes, and snippets.

@anish000kumar
Last active November 22, 2020 10:05
Show Gist options
  • Save anish000kumar/e2f04620b05abafb2e2c9b67c2db380f to your computer and use it in GitHub Desktop.
Save anish000kumar/e2f04620b05abafb2e2c9b67c2db380f to your computer and use it in GitHub Desktop.
Multiply two positive numbers
class Solution:
def getSum(self, nums_list, limit):
# accepts nums_list, array of numbers in reversed order eg, [ [1, 3], [3, 2] ] == 31+23
res = []
iters = [ iter(nums) for nums in nums_list];
carry = 0
for i in range(limit):
val = carry
for _iter in iters: val += next(_iter, 0)
carry, digit = val // 10, val %10
res.append(digit)
res.reverse()
# skip leading zeroes
i = 0;
while i < len(res) and res[i]==0: i++
ans = res[i:]
return ans if len(ans) > 0 else [0];
def getMultiplication(self, first, second):
# accepts two arrays denoting numbers to be multiplied
res = []
for i, s_num in enumerate(reversed(second)):
carry, rowVal = 0, [0] * i
for f_num in reversed(first):
val = f_num * s_num + carry
carry, digit = val // 10, val % 10
rowVal.append(digit)
if carry > 0: rowVal.append(carry)
res.append(rowVal)
return self.getSum(res, len(first) + len(second));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment