Last active
November 30, 2017 12:10
-
-
Save markomanninen/f57e44c0666bf0cfab66a736aade8135 to your computer and use it in GitHub Desktop.
Related discussion: https://codereview.stackexchange.com/questions/181556/multiplying-binary-numbers-digit-by-digit-and-carry-method-in-python
This file contains hidden or 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
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