public static final Map<Character, Integer>?romanMap =new HashMap()
{
????{
????????put('I',1);
????????put('V',5);
????????put('X',10);
????????put('L',50);
????????put('C',100);
????????put('D',500);
????????put('M',1000);
????}
};
/**
* 用于檢驗羅馬數(shù)字規(guī)則的正則表達式
*/
private static final Stringregex ="^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$";
private static final Patternp = Pattern.compile(regex);
/**
* 判斷羅馬數(shù)字字符串是否合規(guī)
* @param s
* @return
*/
public boolean isRomanNumStr(String s) {
????Matcher matcher =p.matcher(s);
????return matcher.find();
}
/**
* 整數(shù)轉(zhuǎn)羅馬數(shù)字
* @param num 0~3999
* @return
*/
public static String intToRomanNum(int num) {
????StringM[] = {"","M","MM","MMM" };
????StringC[] = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM" };
????StringX[] = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC" };
????StringI[] = {"","I","II","III","IV","V","VI","VII","VIII","IX" };
????return M[num /1000] + C[(num %1000) /100] + X[(num %100) /10] + I[num %10];
}
/**
* 羅馬數(shù)字轉(zhuǎn)整數(shù)
* @param romanStr
* @return
*/
public static int romanNumToInt(String romanStr) {
????int result =0;
????int length = romanStr.length();
????// 遍歷羅馬數(shù)字組成的字符串
? ? for(int i=0; i < length-1; i++) {
????????Character current = romanStr.charAt(i);
????????Character next = romanStr.charAt(i+1);
????????//若包含非羅馬數(shù)字咬像,返回-1以標(biāo)識參數(shù)異常情況
? ? ? ? if(romanMap.containsKey(current) &&romanMap.containsKey(next)) {
????????????//羅馬數(shù)字規(guī)則示姿,前小后大 表示 后減前
? ? ? ? ? ? if(romanMap.get(current)>=romanMap.get(next)) {
????????????????result +=romanMap.get(current);
????????????}else {
????????????????result -=romanMap.get(current);
????????????}
????????}else {
????????????return -1;
????????}
????}
????//遍歷時未處理最后一個羅馬數(shù)
? ? result +=romanMap.get(romanStr.charAt(length-1));
????return result;
}