来源:Leetcode Problem Set - Algorithm Problem13
题目描述:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解题思路:与12题类似,读取字符串进行翻译即可,注意到罗马数字的规则里有大字符优先出现,所以如果有小字符出现在大字符左侧,那么它一定是前一个大字符需要减去的元素。
题解代码:
class Solution {
public:
int romanToInt(string s) {
int length = s.length();
if (length < 1) return 0;
map<char,int> m;
m['I'] = 1;
m['V'] = 5;
m['X'] = 10;
m['L'] = 50;
m['C'] = 100;
m['D'] = 500;
m['M'] = 1000;
int i = length - 1;
int sum = m[s[i--]];
while(i >= 0)
if (m[s[i+1]] > m[s[i]])
sum -= m[s[i--]];
else
sum += m[s[i--]];
return sum;
}
};