Roman to Integer - Problem

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

SymbolValue
I1
V5
X10
L50
C100
D500
M1000

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:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (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
Roman to Integer: "XIV" → 14RomanXIVProcess Rules:X = 10 (add)IV = 4 (subtract)I before V = 5-1Integer14Key: I before larger symbol means subtractionXIV = X + (V - I) = 10 + 4 = 14
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
Asked in
Facebook 35 Amazon 28 Microsoft 22 Google 18
219.7K Views
High Frequency
~15 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen