美文网首页
13. Roman to Integer

13. Roman to Integer

作者: weego | 来源:发表于2018-04-05 23:09 被阅读0次

    Description

    Given a roman numeral, convert it to an integer.
    Input is guaranteed to be within the range from 1 to 3999.

    Solution

    和12. Integer to Roman相反,给定一个罗马数字,求对应的阿拉伯数值,注意9、4的情况

    int romanToInt(string s) {
        int ret = 0;
        map<char, int> myMap = {{'M', 1000}, {'D', 500}, {'C', 100}, {'L', 50}, {'X', 10}, {'V', 5}, {'I', 1}};
        for (int i = 0; i< s.length(); ++i) {
            if (i < s.length() - 1 && myMap[s[i]] < myMap[s[i + 1]]) {
                ret += myMap[s[i + 1]] - myMap[s[i]]; //出现9、4的case
                i++;
            } else {
                ret += myMap[s[i]];
            }
        }
        return ret;
    }
    

    相关文章

      网友评论

          本文标题:13. Roman to Integer

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