fork(1) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class RomanToDecimalConverter {
  9. private static double evaluateNextRomanNumeral(String roman, int pos, double rightNumeral) {
  10. if (pos < 0) return 0;
  11. char ch = roman.charAt(pos);
  12. double value = Math.floor(Math.pow(10, "IXCM".indexOf(ch))) + 5 * Math.floor(Math.pow(10, "VLD".indexOf(ch)));
  13. return value * Math.signum(value + 0.5 - rightNumeral) + evaluateNextRomanNumeral(roman, pos - 1, value);
  14. }
  15.  
  16. public static int evaluateRomanNumerals(String s) {
  17. 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})$"))
  18. return -1;
  19. return (int) evaluateNextRomanNumeral(s, s.length() - 1, 0);
  20. }
  21.  
  22. public static void main (String[] args) {
  23. printRomanToDecimal("XCIX");
  24. printRomanToDecimal("MMMCMXCIX");
  25.  
  26. //common error cases found in other solutions
  27. printRomanToDecimal("IIX");
  28. printRomanToDecimal("IIXX");
  29. printRomanToDecimal("ABC");
  30. printRomanToDecimal("IVX");
  31. }
  32.  
  33. private static void printRomanToDecimal(String s) {
  34. //change the conversion method accordingly
  35. int decimal = evaluateRomanNumerals(s);
  36. String output = decimal != -1 ? ""+decimal : "Invalid roman numerals";
  37. System.out.println(s + ": " + output);
  38. }
  39. }
Success #stdin #stdout 0.05s 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