LeetCoder 13. Roman to Integer

来源:互联网 发布:小说书籍知乎 编辑:程序博客网 时间:2024/06/02 02:37

题意

将一串罗马数字转换为阿拉伯数字,刚好是上一道题的颠倒:Integer to Roman

思路

根据罗马数字的规则,发现只要是小的在大的左边的都是大的减小的,小的在大的右边的,都是大的加小的,根据这个规律,遍历字符串即可.

结果

Your runtime beats 15.56 % of cpp submissions.

代码

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