fork(2) 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 int convertRec(String s) {
  10. if (s.isEmpty()) return 0;
  11. if (s.startsWith("M")) return 1000 + convertRec(s.substring(1));
  12. else if (s.startsWith("CM")) return 900 + convertRec(s.substring(2));
  13. else if (s.startsWith("D")) return 500 + convertRec(s.substring(1));
  14. else if (s.startsWith("CD")) return 400 + convertRec(s.substring(2));
  15. else if (s.startsWith("C")) return 100 + convertRec(s.substring(1));
  16. else if (s.startsWith("XC")) return 90 + convertRec(s.substring(2));
  17. else if (s.startsWith("L")) return 50 + convertRec(s.substring(1));
  18. else if (s.startsWith("XL")) return 40 + convertRec(s.substring(2));
  19. else if (s.startsWith("X")) return 10 + convertRec(s.substring(1));
  20. else if (s.startsWith("IX")) return 9 + convertRec(s.substring(2));
  21. else if (s.startsWith("V")) return 5 + convertRec(s.substring(1));
  22. else if (s.startsWith("IV")) return 4 + convertRec(s.substring(2));
  23. else if (s.startsWith("I")) return 1 + convertRec(s.substring(1));
  24. throw new IllegalArgumentException("Unexpected roman numerals");
  25. }
  26.  
  27. public static int convert(String s) {
  28. 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})$"))
  29. return -1;
  30. return convertRec(s);
  31. }
  32.  
  33. public static void main (String[] args) {
  34. printRomanToDecimal("XCIX");
  35. printRomanToDecimal("MMMCMXCIX");
  36.  
  37. //common error cases found in other solutions
  38. printRomanToDecimal("IIX");
  39. printRomanToDecimal("IIXX");
  40. printRomanToDecimal("ABC");
  41. printRomanToDecimal("IVX");
  42. }
  43.  
  44. private static void printRomanToDecimal(String s) {
  45. //change the conversion method accordingly
  46. int decimal = convert(s);
  47. String output = decimal != -1 ? ""+decimal : "Invalid roman numerals";
  48. System.out.println(s + ": " + output);
  49. }
  50. }
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