Convert a Roman numeral string into its integer value.
Roman to Integer
You are given a string representing a Roman numeral. Convert it to the corresponding integer.
Roman numerals use the following symbols:
| Symbol | Value |
|---|---|
| I | 1 |
| V | 5 |
| X | 10 |
| L | 50 |
| C | 100 |
| D | 500 |
| M | 1000 |
Normally, symbols are added from left to right. However, when a smaller value appears before a larger value, it is subtracted instead of added.
Return the integer value of the given Roman numeral.
Input Format
- A single string
srepresenting a Roman numeral. - The numeral contains only the characters
I,V,X,L,C,D, andM.
Output Format
- Return one integer: the decimal value of the Roman numeral.
Constraints
1 <= s.length <= 15is a reasonable interview constraint for this problem.scontains only valid Roman numeral characters.- The input is assumed to be a valid Roman numeral.
Example 1
Input
s = "III"
Output
3
Explanation
Each symbol adds 1, so 1 + 1 + 1 = 3.
Example 2
Input
s = "IV"
Output
4
Explanation
I comes before V, so it is subtracted: 5 - 1 = 4.
Show 1 more example
Example 3
Input
s = "MCMXCIV"
Output
1994
Explanation
M = 1000, CM = 900, XC = 90, and IV = 4, so the total is 1994.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.