fork(4) download
  1. /* package whatever; // don't place package name! */
  2. import java.util.regex.Matcher;
  3. import java.util.regex.Pattern;
  4.  
  5. /* Name of the class has to be "Main" only if the class is public. */
  6. class RomanToDecimalConverter
  7. {
  8. public static void main (String[] args) {
  9. printRomanToDecimal("XCIX");
  10. printRomanToDecimal("MMMCMXCIX");
  11.  
  12. //error cases
  13. printRomanToDecimal("IIX");
  14. printRomanToDecimal("IIXX");
  15. printRomanToDecimal("ABC");
  16. printRomanToDecimal("IVX");
  17. }
  18.  
  19. private static void printRomanToDecimal(String s) {
  20. int decimal = romanToDecimal(s);
  21. String output = decimal != -1 ? ""+decimal : "Invalid roman numerals";
  22. System.out.println(s + ": " + output);
  23. }
  24.  
  25. public static int romanToDecimal(String s) {
  26. if (s == null || s.isEmpty() || !s.matches("^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$"))
  27. return -1;
  28.  
  29. final Matcher matcher = Pattern.compile("M|CM|D|CD|C|XC|L|XL|X|IX|V|IV|I").matcher(s);
  30. final int[] decimalValues = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
  31. final String[] romanNumerals = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
  32. int result = 0;
  33.  
  34. while (matcher.find())
  35. for (int i = 0; i < romanNumerals.length; i++)
  36. if (romanNumerals[i].equals(matcher.group(0)))
  37. result += decimalValues[i];
  38.  
  39. return result;
  40. }
  41. }
Success #stdin #stdout 0.04s 711168KB
stdin
Standard input is empty
stdout
XCIX: 99
MMMCMXCIX: 3999
IIX: Invalid roman numerals
IIXX: Invalid roman numerals
ABC: Invalid roman numerals
IVX: Invalid roman numerals