[LeetCode] Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

将一串罗马数字转换为整数,首先使用map建立罗马字母与数字的表示法则。然后从右向左遍历罗马字符串,根据罗马计数法则:

1)相同的数字连写,所表示的数等于这些数字相加得到的数。

2)小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数。

3)小的数字(仅限L, X, C)在大的数字左边,所表示的数等于大数减去小数得到的数。

用if语句判断1),2)和3)即可。

class Solution {
public:
    int romanToInt(string s) {
        unordered_map<char, int> m = {{'I', 1}, 
                                      {'V', 5}, 
                                      {'X', 10}, 
                                      {'L', 50}, 
                                      {'C', 100}, 
                                      {'D', 500}, 
                                      {'M', 1000}
                                     };
        int n = s.size();
        int res = m[s[n - 1]];
        for (int i = n - 2; i >= 0; i--) {
            if (m[s[i]] < m[s[i + 1]])
                res -= m[s[i]];
            else
                res += m[s[i]];
        }
        return res;
    }
};
// 105 ms
原文地址:https://www.cnblogs.com/immjc/p/7194822.html