您的位置:首页 > 其它

LeetCode | 13. Roman to Integer

2017-04-09 16:50 302 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode