Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
很无聊的一道题,不过也是涨姿势了,原来罗马数字是这么一个规则。
class Solution {
public:
int toNum(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;
}
}
int romanToInt(string s) {
int ret = 0;
for (int i = 0; i < s.size(); i++) {
if (i + 1 < s.size()) {
if(toNum(s[i]) < toNum(s[i+1]))
ret -= toNum(s[i]);
else
ret += toNum(s[i]);
}
else
ret += toNum(s[i]);
}
return ret;
}
};