Last active
July 16, 2018 13:54
-
-
Save sergicastro/2455c8bfa63e90300802224cb12ccedf to your computer and use it in GitHub Desktop.
fromRomanToDec
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
private static int toDecimal(final String roman) | |
{ | |
String[] chars = roman.split("(?!^)"); | |
int d = 0; | |
ROMAN last = null; | |
// the trick is run the sequence from right to left | |
for (int i = chars.length - 1; i >= 0; i--) | |
{ | |
String c = chars[i]; | |
ROMAN r = ROMAN.valueOf(c.toUpperCase()); | |
// ordrinal returns the index as declared in enum, p.e: I=0,V=1,X=3 | |
// so we can know if a char has a greater value than an other | |
// then: | |
// if last char is lower than actual, we keep using adding the value | |
if (last == null || last.ordinal() <= r.ordinal()) | |
{ | |
d += r.decimal; | |
} | |
// if the last bigger than the actual, we substract its value, | |
// p.e: IX -> last = X and actual = I -> X - I | |
else | |
{ | |
d -= r.decimal; | |
} | |
last = r; | |
} | |
return d; | |
} | |
enum ROMAN | |
{ | |
I(1), V(5), X(10), L(50), C(100), D(500), M(1000); | |
final int decimal; | |
private ROMAN(final int decimal) | |
{ | |
this.decimal = decimal; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment