13. Roman to Integer

来源:互联网 发布:阿里云服务器 翻墙 编辑:程序博客网 时间:2024/05/29 03:16
Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999.Subscribe to see which companies asked this question.

这道题没什么难的,唯一难的就是鬼知道罗马数字都有什么。

实际上对于罗马数字举例:4->IV,而6->VI,可见我们从右边往左边遍历,如果A[i]< A[i+1],我们的res要减去这个值即可。否则就一直累加,最终得到最终结果。

class Solution {public:    int romanToInt(string s) {        unordered_map<char, int> umap = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},                                         {'C', 100}, {'D', 500}, {'M', 1000}};        const int len = s.length();        int res = umap[s[len-1]];        for(int i=len-2; i>=0; --i) {            if(umap[s[i]] < umap[s[i+1]])                res -= umap[s[i]];            else                 res += umap[s[i]];        }        return res;    }};
0 0
原创粉丝点击