Roman to integer

Add each symbol's value, except when a smaller symbol sits just before a larger one: then subtract it instead.

Time O(n)Space O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Normally roman numerals are read left to right and added up. The one exception is a subtractive pair like IV or XC, where a smaller symbol just before a larger one means "subtract the smaller". Checking one symbol ahead catches every such pair in a single left-to-right pass.

Code

public static int RomanToInt(string s) {
    var val = new Dictionary<char, int> { ['I']=1,['V']=5,['X']=10,['L']=50,['C']=100,['D']=500,['M']=1000 };
    int total = 0;
    for (int i = 0; i < s.Length; i++) {
        int cur = val[s[i]];
        if (i + 1 < s.Length && cur < val[s[i + 1]])
            total -= cur;
        else
            total += cur;
    }
    return total;
}
static int romanToInt(String s) {
    Map<Character, Integer> val = Map.of('I', 1, 'V', 5, 'X', 10, 'L', 50, 'C', 100, 'D', 500, 'M', 1000);
    int total = 0;
    for (int i = 0; i < s.length(); i++) {
        int cur = val.get(s.charAt(i));
        if (i + 1 < s.length() && cur < val.get(s.charAt(i + 1)))
            total -= cur;
        else
            total += cur;
    }
    return total;
}
int romanToInt(const string& s) {
    unordered_map<char, int> val = {{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};
    int total = 0;
    for (int i = 0; i < (int)s.size(); i++) {
        int cur = val[s[i]];
        if (i + 1 < (int)s.size() && cur < val[s[i + 1]])
            total -= cur;
        else
            total += cur;
    }
    return total;
}
def roman_to_int(s: str) -> int:
    val = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
    total = 0
    for i in range(len(s)):
        cur = val[s[i]]
        if i + 1 < len(s) and cur < val[s[i + 1]]:
            total -= cur
        else:
            total += cur
    return total

Tips

In the .NET library

There is no built-in conversion in .NET. A lookup table plus this one-ahead check is the standard approach, and it naturally rejects nothing, so malformed input should be validated separately if needed.