[leetcode] Roman to integer

Given a roman numeral, convert it to an integer.

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

其实一个一个加就行,例如IV是4,但直接加的结果是6,这个时候减去2就行。
class Solution {
public:
    int romanToInt(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        map<char, int> roman;
        roman.insert(make_pair('I', 1));
        roman.insert(make_pair('V', 5));
        roman.insert(make_pair('X', 10));
        roman.insert(make_pair('L', 50));
        roman.insert(make_pair('C', 100));
        roman.insert(make_pair('D', 500));
        roman.insert(make_pair('M', 1000));
        
        int n = s.size();
        int pre = 10000;
        int res = 0;
        int cur = 0;
        for(int i = 0 ;i < n; ++i){
            cur = roman[s[i]];
            res += cur;
            if(cur > pre){
                res -= 2*pre;
            }
            pre = cur;
        }
        return res;
    }
};


猜你喜欢

转载自blog.csdn.net/selera/article/details/23689379