Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:
字母对数字的一一对应累积关系。唯一需要注意的是,之前一个字母对应的数字如果小于当前字母对应的数字,则需要特殊处理。
题解:
std::map<char, int> char_mapper{ {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000} }; class Solution { public: int romanToInt(string s) { int value = 0; char last = s[0]; for(auto ch : s) { if (char_mapper[last] < char_mapper[ch]) { // meet the special case value -= char_mapper[last] * 2; value += char_mapper[ch]; } else value += char_mapper[ch]; last = ch; } return value; } };