Last active
August 29, 2015 14:21
-
-
Save ahirschberg/4961d4d20de994df5954 to your computer and use it in GitHub Desktop.
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment