Integer to Roman
Medium · Math · Hash Table · Math · String · Greedy
Problem
Convert an integer num into its Roman numeral form. The symbols are I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000.
Build the numeral one decimal place at a time, from the highest place down:
- A digit of 4 or 9 is written with a subtractive pair: IV (4), IX (9), XL (40), XC (90), CD (400), CM (900).
- Only I, X, C and M may repeat, and at most three times in a row. V, L and D never repeat; use the subtractive form instead.
Return the Roman numeral as a string.
Examples
Input: num = 58 Output: "LVIII"
50 is L and 8 is VIII.
Input: num = 944 Output: "CMXLIV"
900 is CM, 40 is XL and 4 is IV.
Input: num = 3006 Output: "MMMVI"
3000 is MMM, the zero hundreds and tens add nothing, and 6 is VI.
Constraints
- 1 <= num <= 3999
Approaches
- Baseline: additive numeral, then rewrite — time O(1), space O(1)
Follow-up
Going the other way, from a numeral back to its value, is a single left-to-right scan: add each symbol, but subtract it when a larger symbol follows it. That is the first use case below.
Related problems
Start free on Cariara · Coding problems · System design studio