`

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics