Roman to Integer - Problem
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
| Symbol | Value |
|---|---|
| I | 1 |
| V | 5 |
| X | 10 |
| L | 50 |
| C | 100 |
| D | 500 |
| M | 1000 |
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(1000) to make 400 and 900.
Given a roman numeral string s, convert it to an integer.
Input & Output
Example 1 — Basic Roman Numeral
$
Input:
s = "III"
›
Output:
3
💡 Note:
III = 3 (simple addition: 1 + 1 + 1 = 3)
Example 2 — Subtraction Case
$
Input:
s = "IV"
›
Output:
4
💡 Note:
IV = 4 (subtraction case: I before V means 5 - 1 = 4)
Example 3 — Mixed Operations
$
Input:
s = "MCMXC"
›
Output:
1990
💡 Note:
M = 1000, CM = 900 (1000-100), XC = 90 (100-10), so 1000 + 900 + 90 = 1990
Constraints
- 1 ≤ s.length ≤ 15
- s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M')
- It is guaranteed that s is a valid roman numeral in the range [1, 3999]
Visualization
Tap to expand
Understanding the Visualization
1
Input
Roman numeral string with symbols I,V,X,L,C,D,M
2
Process
Handle addition and subtraction rules
3
Output
Integer value of the Roman numeral
Key Takeaway
🎯 Key Insight: Process right-to-left comparing values - smaller before larger means subtraction
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code