LeetCode 13 - Roman to Integer

Given a roman numeral, convert it to an integer.

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

int romanToInt(string s) {
    unordered_map<char,int> map = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
    int num = 0;
    for(int i=0; i<s.size(); i++) {
        if(i<s.size()-1 && map[s[i]]<map[s[i+1]]) {
            num += map[s[i+1]] - map[s[i]];
            i++;
        } else {
            num += map[s[i]];
        }
    }
    return num;
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2218543