Convert a Roman numeral to an integer
Convert a valid Roman numeral using I, V, X, L, C, D, and M to its integer value.
Course progress
Problem 66 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
roman = "MCMXCIV"
Expected output
1994
What is happening?
M = 1000, CM = 900, XC = 90, and IV = 4. Adding those parts gives 1994.
Solution strategy
Build the right mental model
Add each symbol unless its value is smaller than the following symbol; in that subtractive case, subtract it instead.
Core concepts
strings · dictionary
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for roman-numeral-to-integer
using System;
using System.Collections.Generic;
class Program
{
static int RomanToInteger(string roman)
{
var values = 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 < roman.Length; i++)
{
int value = values[roman[i]];
total += i + 1 < roman.Length && value < values[roman[i + 1]] ? -value : value;
}
return total;
}
static void Main()
{
Console.WriteLine(RomanToInteger("MCMXCIV"));
}
}Knowledge check
Questions students often ask
What is the main idea behind convert a roman numeral to an integer?
Add each symbol unless its value is smaller than the following symbol; in that subtractive case, subtract it instead.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.