美文网首页
13. Roman to Integer

13. Roman to Integer

作者: wangdsh | 来源:发表于2019-08-27 10:54 被阅读0次

    题目地址:https://leetcode.com/problems/roman-to-integer/
    思路:从左到右遍历,把当前字符对应数字累加到结果中,如果当前数比上一个数大,则需要减去上一个数的2倍。

    class Solution {
    public:
        int romanToInt(string s) {
            map<char, int> foo;
            foo['I'] = 1;
            foo['V'] = 5;
            foo['X'] = 10;
            foo['L'] = 50;
            foo['C'] = 100;
            foo['D'] = 500;
            foo['M'] = 1000;
            
            int result = 0;
            int len = s.length();
            for (int i=0; i<len; i++) {
                result += foo[(s[i])];
                if ((i-1 >=0) && (foo[s[i]] - foo[s[i-1]]) > 0) {
                    result -= 2 * foo[s[i-1]];
                }
            }
            return result;
        }
    };
    
    Runtime Memory
    12 ms 10.5 MB

    相关文章

      网友评论

          本文标题:13. Roman to Integer

          本文链接:https://www.haomeiwen.com/subject/wpbsectx.html