I implemented this in ruby!
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
def multiply(number1, number2) | |
# convert number1 to binary and reverse it | |
# so that the most significant bit is last | |
n1_binary_str = number1.to_s(2).reverse | |
binary_array = n1_binary_str.split '' # convert string to array | |
add_amount = nil | |
total = 0 | |
binary_array.each_with_index do |char, index| | |
# double the add_amount, or set it to number2 if it is nil | |
add_amount = add_amount ? (add_amount + add_amount) : number2 | |
# add add_amount to the total if the binary for | |
# number2 has a binary 1 in given place | |
total += add_amount if char == '1' | |
end | |
return total | |
end |
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
multiply 1, 2 | |
#=> 2 | |
multiply 400, 2 | |
#=> 800 | |
multiply 400, 20 | |
#=> 8000 | |
multiply 400, 200 | |
#=> 80000 |
View it in action here by pressing the run button
The full code I wrote is here, which is extensible in case I get around to testing the efficiency of this algorithm compared to other methods.
No comments:
Post a Comment