问题来源:https://leetcode.com/problems/roman-to-integer/
/**
*
* <p>
* ClassName RomanToInteger
* </p>
* <p>
* Description Given a roman numeral, convert it to an integer.
*
* Input is guaranteed to be within the range from 1 to 3999.
* </p>
*
* @author TKPad wangx89@126.com
* <p>
* Date 2015年3月26日 下午8:53:39
* </p>
* @version V1.0.0
*
*/
public class RomanToInteger {
public int romanToInt(String s) {
if (null == s || "".equals(s)) {
return 0;
}
int result = 0;
boolean isNext = false;
char[] charArray = s.trim().toCharArray();
int i = 0;
for (; i < charArray.length - 1; i++) {
int temp1 = charToInt(charArray[i]);
int temp2 = charToInt(charArray[i + 1]);
if (temp1 < temp2) {
isNext = true;// 将两个连起来解析
}
if (isNext) {
result += (temp2 - temp1);
i++;
isNext = false;
} else {
result += temp1;
}
}
if (i == charArray.length - 1) {
// 处理最后一个
result += charToInt(charArray[i]);
}
return result;
}
public int charToInt(char c) {
switch (c) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
public static void main(String[] args) {
int romanToInt = new RomanToInteger().romanToInt("MM");
System.out.println(romanToInt);
}
}