Last active
November 22, 2020 10:05
-
-
Save anish000kumar/e2f04620b05abafb2e2c9b67c2db380f to your computer and use it in GitHub Desktop.
Multiply two positive numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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