13. 罗马数字转整数 【简单模拟】

思路:

正常顺序:前大后小;

遍历数组,若发现当前字符对应的数字比后面的小的话,就让当前值取相反数。

代码:

class Solution {
public:
    int romanToInt(string s) {
        map mp;
        mp['I'] = 1;
        mp['V'] = 5;
        mp['X'] = 10;
        mp['L'] = 50;
        mp['C'] = 100;
        mp['D'] = 500;
        mp['M'] = 1000;

        int len = s.length();
        int sum = 0;
        for (int i = 0; i < len; i++) {
            int value = mp[s[i]];
            if (i < len - 1 && mp[s[i]] < mp[s[i+1]]) {
                value = -value;
            }
            sum += value;
        }
        return sum;
    }
}; 

你可能感兴趣的:(leetcode)