LeetCode-13 Roman to Integer

题目链接

分析:当I出现在V前,即-1 + 5 = 4
所以当字符x代表的数字小于其后字符y代表的数字时,x所代表的数字取负

C++

class Solution {
public:
    int romanToInt(string s) {
        map<char, int> 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 - 1; i++)
        {
            if (mp[s[i]] >= mp[s[i + 1]])
            {
                sum += mp[s[i]];
            }
            else
            {
                sum -= mp[s[i]];
            }
        }
        
        return sum + mp[s[len - 1]];
    }
};

猜你喜欢

转载自blog.csdn.net/qq_30986521/article/details/80819514