Created
April 16, 2009 12:01
-
-
Save kron4eg/96385 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
class BaseConverter | |
def initialize(digits) | |
@decimal_digits = "0123456789" | |
@digits = digits.to_s | |
end | |
def from_decimal(i) | |
convert(i.to_s, @decimal_digits, @digits) | |
end | |
def to_decimal(s) | |
convert(s.to_s, @digits, @decimal_digits) | |
end | |
def convert(number, fromdigits, todigits) | |
neg = false | |
if number[0].chr == '-' | |
neg = true | |
number.slice!(/^./) | |
end | |
x = 0 | |
number.to_s.each_char do |digit| | |
x = x * fromdigits.length + fromdigits.index(digit) | |
end | |
return todigits[0].chr if x == 0 | |
res = "" | |
while x > 0 | |
digit = x % todigits.length | |
res = todigits[digit].chr + res | |
x = (x / todigits.length).to_i | |
end | |
res = '-' + res if neg | |
return res | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment