Roman to integer
Add each symbol's value, except when a smaller symbol sits just before a larger one: then subtract it instead.
Watch it animatedStep through it, with the running line highlighted. Free with an account.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;
}Tips
- Only the current symbol needs to look ahead by one; nothing needs to look backward.
- MCMXCIV demonstrates all three subtractive pairs used in practice: CM, XC and IV.
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.