问题
Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.
分析:
如果当前处理的字符对应的值和上一个字符一样,那么临时变量加上这个字符。比如III = 3如果当前比前一个大,说明这一段的值应该是当前这个值减去前面记录下的临时变量中的值。比如IIV = 5 – 2如果当前比前一个小,那么就可以先将临时变量的值加到结果中,然后开始下一段记录。比如VI = 5 + 1
int romanToInt(std::string s){
if (s.length() <
1)
return 0;
int result =
0;
int sum = toInt(s[
0]);
int end = toInt(s[
0]);
for (
int i =
1; i < s.length(); ++i) {
int current = toInt(s[i]);
if (current == end)
sum += current;
else if (current < end) {
result +=
sum;
sum = current;
}
else {
sum = current - end;
}
end = current;
}
result +=
sum;
return result;
}
int toInt(
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;
}
}