Created
January 15, 2017 07:02
-
-
Save tangmae/7d53d399294769fee25a22ec9685e3d0 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 RomanNumerals | |
@roman = "IVXLCDM" | |
@numeric = [1,5,10,50,100,500,1000] | |
def self.to_roman(int) | |
index = int.to_s.size() | |
ans = "" | |
for i in 0..index-1 | |
c = int.to_s[i].to_i | |
value = 10**(index-1) | |
if (c == 9 || c == 4) && !(c*value > 1000) | |
ans += @roman[@numeric.index(value)] + @roman[@numeric.index(value*(1+c))] | |
elsif c > 5 | |
ans += @roman[@numeric.index(value*5)] + (@roman[@numeric.index(value)]*(c-5)) | |
elsif c == 5 | |
ans += @roman[@numeric.index(value*c)] | |
elsif c != 0 | |
ans += @roman[@numeric.index(value)]*c | |
end | |
index -= 1 | |
end | |
ans | |
end | |
def self.from_roman(roman) | |
ans = [] | |
roman.split("").each do |c| | |
if ans != [] && @numeric[@roman.index(c)] > ans.last | |
ans[ans.size()-1] = ans.last*-1 | |
end | |
ans.push(@numeric[@roman.index(c)]) | |
end | |
ans.reduce(:+) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment