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.

BASIC Character
I
V
X
L
C
D
M
Arabic numerals
1
5
10
50
100
500
1000

the rule is complex,but in this condition. It can be tell as:

we start from the end of String.
if the char before the current char we are reading: add it
if not: subtract it。

Code

class Solution {
public:
    int romanToInt(string s) {

        unordered_map <char,int> map = {
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000} };

        int sum = 0, n = s.size();
        for(int i = 0; i < n; i ++){
            if(i == n - 1) sum += map[s[i]];
            else{
                sum += (map[s[i]] < map[s[i+1]])?-map[s[i]]:map[s[i]];
            }
        }        
        return sum;
    }
};

results matching ""

    No results matching ""