Easy
Roman Numerals Chart
从后往前traverse,这道题注意一下"I", "X", "C"这几个代表1,10,100的罗马数字在原数字大于5,大于50,大于500时都是做减法的,所以要讨论。并且注意一下switch case的写法。
class Solution {
public int romanToInt(String s) {
int res = 0;
for (int i = s.length() - 1; i >= 0; i--){
char c = s.charAt(i);
switch (c) {
case 'I':
res += (res >= 5 ? -1 : 1);
break;
case 'V':
res += 5;
break;
case 'X':
res += (res >= 50 ? -10 : 10);
break;
case 'L':
res += 50;
break;
case 'C':
res += (res >= 500 ? - 100 : 100);
break;
case 'D':
res += 500;
break;
case 'M':
res += 1000;
break;
}
}
return res;
}
}