Skip to content

Instantly share code, notes, and snippets.

@ahirschberg
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahirschberg/4961d4d20de994df5954 to your computer and use it in GitHub Desktop.
Save ahirschberg/4961d4d20de994df5954 to your computer and use it in GitHub Desktop.
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
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