/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class RomanToDecimalConverter {
private static double evaluateNextRomanNumeral
(String roman,
int pos,
double rightNumeral
) { if (pos < 0) return 0;
char ch = roman.charAt(pos);
double value
= Math.
floor(Math.
pow(10,
"IXCM".
indexOf(ch
))) + 5 * Math.
floor(Math.
pow(10,
"VLD".
indexOf(ch
))); return value
* Math.
signum(value
+ 0.5 - rightNumeral
) + evaluateNextRomanNumeral
(roman, pos
- 1, value
); }
public static int evaluateRomanNumerals
(String s
) { 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})$"))
return -1;
return (int) evaluateNextRomanNumeral(s, s.length() - 1, 0);
}
public static void main
(String[] args
) { printRomanToDecimal("XCIX");
printRomanToDecimal("MMMCMXCIX");
//common error cases found in other solutions
printRomanToDecimal("IIX");
printRomanToDecimal("IIXX");
printRomanToDecimal("ABC");
printRomanToDecimal("IVX");
}
private static void printRomanToDecimal
(String s
) { //change the conversion method accordingly
int decimal = evaluateRomanNumerals(s);
String output
= decimal
!= -1 ? ""+decimal
: "Invalid roman numerals"; System.
out.
println(s
+ ": " + output
); }
}
LyogcGFja2FnZSB3aGF0ZXZlcjsgLy8gZG9uJ3QgcGxhY2UgcGFja2FnZSBuYW1lISAqLwoKaW1wb3J0IGphdmEudXRpbC4qOwppbXBvcnQgamF2YS5sYW5nLio7CmltcG9ydCBqYXZhLmlvLio7CgovKiBOYW1lIG9mIHRoZSBjbGFzcyBoYXMgdG8gYmUgIk1haW4iIG9ubHkgaWYgdGhlIGNsYXNzIGlzIHB1YmxpYy4gKi8KY2xhc3MgUm9tYW5Ub0RlY2ltYWxDb252ZXJ0ZXIgewogICAgcHJpdmF0ZSBzdGF0aWMgZG91YmxlIGV2YWx1YXRlTmV4dFJvbWFuTnVtZXJhbChTdHJpbmcgcm9tYW4sIGludCBwb3MsIGR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