问题链接
Roman to Integer | LeetCode OJ
问题描述
把一个罗马数字转换为普通数字。
解决办法
public class Solution {
public int romanToInt(String s) {
int lastCharNumber = 0;
int result = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int currentCharNumber = romanCharToInt(c);
if(lastCharNumber < currentCharNumber){
result -= lastCharNumber;
result += (currentCharNumber - lastCharNumber);
}
else{
result += currentCharNumber;
}
lastCharNumber = currentCharNumber;
}
return result;
}
public static int romanCharToInt(char c) throws NumberFormatException {
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;
}
throw new NumberFormatException("Illegal char " + String.valueOf(c));
}
}