LeetCode | 13. Roman to Integer

来源:互联网 发布:pe系统制作软件 编辑:程序博客网 时间:2024/06/05 19:42

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

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