天天看點

[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;
    }
};