13. Roman to Integer

来源:互联网 发布:ubuntu磁盘一直不足 编辑:程序博客网 时间:2024/05/01 16:23

Given a roman numeral, convert it to an integer.

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

solution:

class Solution {public:    int romanToInt(string s) {        map<char,int> m;        m['I'] = 1;        m['V'] = 5;        m['X'] = 10;        m['L'] = 50;        m['C'] = 100;        m['D'] = 500;        m['M'] = 1000;        int res = 0;        if(s.empty()) return 0;        for(int i=0; i<s.size();i++){            res += m[s[i]];            if(i>0&&m[s[i]]>m[s[i-1]]) res = res-2*m[s[i-1]];        }        return res;    }};
心得:了解罗马计数的规则就好了

0 0
原创粉丝点击