Description
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Solution
和12. Integer to Roman相反,给定一个罗马数字,求对应的阿拉伯数值,注意9、4的情况
int romanToInt(string s) {
int ret = 0;
map<char, int> myMap = {{'M', 1000}, {'D', 500}, {'C', 100}, {'L', 50}, {'X', 10}, {'V', 5}, {'I', 1}};
for (int i = 0; i< s.length(); ++i) {
if (i < s.length() - 1 && myMap[s[i]] < myMap[s[i + 1]]) {
ret += myMap[s[i + 1]] - myMap[s[i]]; //出现9、4的case
i++;
} else {
ret += myMap[s[i]];
}
}
return ret;
}
网友评论