Integer to Roman - Problem

Convert an integer to its Roman numeral representation using the seven basic symbols:

Symbol Values:

  • I = 1
  • V = 5
  • X = 10
  • L = 50
  • C = 100
  • D = 500
  • M = 1000

Conversion Rules:

  • Use largest possible values first (greedy approach)
  • Special subtractive cases: IV (4), IX (9), XL (40), XC (90), CD (400), CM (900)
  • Only append symbols consecutively up to 3 times (I, X, C, M)
  • Never repeat V, L, D multiple times

Given an integer between 1 and 3999, return its Roman numeral string.

Input & Output

Example 1 — Standard Conversion
$ Input: num = 3
Output: III
💡 Note: 3 is represented as III (three ones: I + I + I = III)
Example 2 — Subtractive Case
$ Input: num = 58
Output: LVIII
💡 Note: 58 = 50 + 8 = L + VIII (50 as L, 8 as V + III)
Example 3 — Complex Number
$ Input: num = 1994
Output: MCMXCIV
💡 Note: 1994 = 1000 + 900 + 90 + 4 = M + CM + XC + IV

Constraints

  • 1 ≤ num ≤ 3999

Visualization

Tap to expand
Integer to Roman Conversion INPUT num = 3 Roman Symbols Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000 IV, IX... 4, 9... ALGORITHM STEPS 1 Initialize result = "" (empty string) remaining = 3 2 Greedy Loop Start from largest (M=1000) Check: 3 >= 1000? No Skip D, C, L, X, V... 3 Match Found Check: 3 >= 1? Yes! Append "I", subtract 1 remaining = 2 4 Repeat 2 >= 1? Add "I" --> rem=1 1 >= 1? Add "I" --> rem=0 rem=0, loop ends Iterations: "" --> "I" --> "II" --> "III" FINAL RESULT Roman Numeral: III Visual Breakdown: I =1 + I =1 + I =1 = 3 OK - Verified! Key Insight: The greedy approach works because Roman numerals are designed with values that allow optimal representation. Always subtract the largest possible value first. Special cases (IV=4, IX=9, XL=40, XC=90, CD=400, CM=900) are pre-computed in the value-symbol pairs. TutorialsPoint - Integer to Roman | Greedy with Value-Symbol Pairs
Asked in
Microsoft 45 Amazon 38
78.0K Views
Medium Frequency
~15 min Avg. Time
2.8K 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