Skip to content

Instantly share code, notes, and snippets.

@markomanninen
Last active November 30, 2017 12:10
Show Gist options
  • Save markomanninen/f57e44c0666bf0cfab66a736aade8135 to your computer and use it in GitHub Desktop.
Save markomanninen/f57e44c0666bf0cfab66a736aade8135 to your computer and use it in GitHub Desktop.
def is_zero(n):
return not n[1:] and not n[0]
def carry_over(first_num, second_num):
stack = []
for i, j in enumerate(second_num):
if j:
# basicly same as map(sum, zip(stack, a)) but with zero appends
stack = [(stack.pop(0) + n) if stack else n \
for n in ([0] * i + first_num)]
overflow = 0
for i, j in enumerate(stack):
overflow, stack[i] = divmod(j + overflow, 2)
while overflow > 0:
stack.append(overflow % 2)
overflow //= 2
return stack
def multiply(first_num, second_num):
if is_zero(first_num) or is_zero(second_num):
return [0]
else:
return carry_over(first_num, second_num)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment