Created
November 24, 2016 04:26
-
-
Save metal-hed/0999ac3d405f22b02630177db3834d98 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
/** | |
* Created by Nicolo on 24/10/2016. | |
*/ | |
public class Roman { | |
private enum Numerals { | |
I(1), | |
V(5), | |
X(10), | |
L(50), | |
C(100), | |
D(500), | |
M(1000); | |
private int decimal; | |
public int getDecimal() { | |
return decimal; | |
} | |
Numerals(int decimal) { | |
this.decimal = decimal; | |
} | |
} | |
private static int romanToDecimal(String romanNumeral) { | |
if (romanNumeral.length() <= 1) { | |
return getCharValue(romanNumeral); | |
} | |
int rank = Integer.MIN_VALUE; | |
int position = 0; | |
for (int i = 0; i < romanNumeral.length(); i++) { | |
String c = String.valueOf(romanNumeral.charAt(i)); | |
int value = getCharValue(c); | |
if (value > rank) { | |
rank = value; | |
position = i; | |
} | |
} | |
if (position == 0) { | |
// Start of string, process from second character and on | |
return rank + romanToDecimal(romanNumeral.substring(position + 1)); | |
} else { | |
String restOfIt = romanNumeral.substring(0, position); | |
if (position == romanNumeral.length() - 1) { | |
// End of string, process from start of string to the 2nd last letter | |
return rank - romanToDecimal(restOfIt); | |
} else { | |
// Letters on both sides, subtract the left, add the right | |
return rank - romanToDecimal(restOfIt) + romanToDecimal(romanNumeral.substring(position + 1, romanNumeral.length())); | |
} | |
} | |
} | |
private static int getCharValue(String roman) { | |
try { | |
Numerals romanNumeral = Numerals.valueOf(roman.toUpperCase()); | |
return romanNumeral.getDecimal(); | |
} catch (IllegalArgumentException e) { | |
System.out.println("The letter [" + roman + "] is not a valid roman numeral"); | |
System.exit(1); | |
return 1; | |
} | |
} | |
/** | |
* | |
*/ | |
public static void main(String[] args) { | |
System.out.println(romanToDecimal("MMMMDCCLXXXV")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment