Created
August 29, 2013 00:55
-
-
Save broguinn/6373150 to your computer and use it in GitHub Desktop.
binary
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 binary(binary_string) | |
if !(binary_string.is_a?(String)) || binary_string.match(/[^0,1]/) | |
raise TypeError.new("Input must be only 0s and 1s") | |
end | |
total = 0 | |
binary_string.reverse.split("").each_with_index do |bit, index| | |
total += bit.to_i * 2 ** index | |
end | |
total | |
end | |
def trinary(trinary_string) | |
if !(trinary_string.is_a?(String)) || trinary_string.match(/[^0,1,2]/) | |
raise TypeError.new("Input must be only 0s and 1s and 2s") | |
end | |
total = 0 | |
trinary_string.reverse.split("").each_with_index do |bit, index| | |
total += bit.to_i * 3 ** index | |
end | |
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
def binary(binary_string) | |
if !(binary_string.is_a?(String)) || binary_string.match(/[^0,1]/) | |
raise TypeError.new("Input must be only 0s and 1s") | |
end | |
total = 0 | |
binary_string.reverse.split("").each_with_index do |bit, index| | |
total += bit.to_i * 2 ** index | |
end | |
total | |
end | |
def trinary(trinary_string) | |
if !(trinary_string.is_a?(String)) || trinary_string.match(/[^0,1,2]/) | |
raise TypeError.new("Input must be only 0s and 1s and 2s") | |
end | |
total = 0 | |
trinary_string.reverse.split("").each_with_index do |bit, index| | |
total += bit.to_i * 3 ** index | |
end | |
total | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment