Integer to Roman
viaLeetCode
Problem Convert an integer (1 to 3999) to a Roman numeral, handling subtractive notation (IV, IX, XL, XC, CD, CM).
Input / Output
- Input: int num. Output: Roman numeral string.
Constraints
- 1 <= num <= 3999 (classic range).
Example
- 1994 → "MCMXCIV" (M + CM + XC + IV); 58 → "LVIII".
Expected approach
- Greedy over 13 value–symbol pairs including the subtractive ones — [1000 M, 900 CM, 500 D, 400 CD, 100 C, 90 XC, 50 L, 40 XL, 10 X, 9 IX, 5 V, 4 IV, 1 I]: repeatedly subtract the largest value ≤ num, appending its symbol. Embedding subtractive pairs in the table is what keeps the code branch-free. O(1). The inverse (roman → int, subtract when a smaller value precedes a larger) is a common follow-on.
asked …