15% off all plans & roadmaps Use code
See plansInteger to Roman
- LeetCode 12
- Medium
- String Manipulation Patterns
- Integer and Roman Conversion
Updated
TL;DR: Convert an integer from 1 to 3999 into a Roman numeral. Walk a table of 13 value-symbol pairs from largest to smallest and take each pair as many times as it fits.
Problem
Roman numerals use seven 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 |
A numeral adds symbol values together. For example, 2 is II, two ones added together. 12 is XII, which is X + II. The number 27 is XXVII, which is XX + V + II.
Numerals are usually written from largest to smallest, reading left to right. The number four is not IIII. It is IV, because the one comes before the five and is subtracted. Nine is written IX for the same reason. Subtraction appears in exactly six cases:
Ican go beforeV(5) andX(10) to make 4 and 9.Xcan go beforeL(50) andC(100) to make 40 and 90.Ccan go beforeD(500) andM(1000) to make 400 and 900.
Given an integer, convert it to a Roman numeral.
Example 1
Input: num = 3 Output: "III"
Example 2
Input: num = 4 Output: "IV"
Example 3
Input: num = 9 Output: "IX"
Example 4
Input: num = 58 Output: "LVIII" Explanation: L = 50, V = 5, III = 3.
Example 5
Input: num = 1994 Output: "MCMXCIV" Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Constraints
1 <= num <= 3999
Constraints that matter
numis at most 3999, so the longest numeral has 15 characters (for example 3888, which is MMMDCCCLXXXVIII). A table of fixed size and fixed-length work is enough.numis at least 1, so there is no zero and no negative input. Roman numerals have no zero symbol, so you never need an empty numeral for a valid input.- Each decimal place of the number maps to one of ten patterns (0 to 9). That lets you index a small table per place instead of building letters from scratch.
- Every subtractive pair has a fixed value. Including the six pairs in the table removes every special case from the loop.
Hints
Hint 1
The clue is the rule that numerals are written largest to smallest.
Hint 2
A beginner usually splits the number into thousands, hundreds, tens and ones, then writes a separate list of cases for each place.
Solution
Intuition
The clue is the rule that numerals are written largest to smallest. Each symbol value is a fixed chunk, and the numeral is the list of chunks that add up to the input. When you must split a number into fixed chunks with the biggest chunk first, the pattern is greedy: take the largest chunk that fits, subtract it, and repeat on the remainder.
It is like making change from a cash drawer. The 13 pairs are the denominations, the result is the list of coins you hand over, and num is the amount still owed.
Subtraction is the only tricky part. Instead of writing a rule for when a smaller symbol comes first, treat IV, IX, XL, XC, CD and CM as chunks with their own values. Then every chunk is a plain value, and the loop never needs a special case.
The greedy choice is safe here because the 13 pairs are exactly the pieces standard notation uses. Taking the largest pair that fits never leaves a remainder that needs a bigger piece. Each step therefore writes the next correct symbols, and the loop ends with a remainder of 0.
Worked example
Input: num = 3999 Output: "MMMCMXCIX" Explanation: The thousands place is 3, so it gives MMM. The hundreds place is 9, which gives CM. The tens place is 9, which gives XC. The ones place is 9, which gives IX. Joined in order, the pieces form MMMCMXCIX.
Approach 1: Brute force: per-digit tables
A beginner usually splits the number into thousands, hundreds, tens and ones, then writes a separate list of cases for each place. Each list maps one digit to its letters, such as 4 to CD in the hundreds place. The code is correct, but it repeats the same mapping pattern four times, and the cases are easy to mistype.
This version does not walk the value table at all. It handles each place on its own, so the subtractive pairs live in four different lists. The approach still works because a decimal digit has only ten possible patterns at each place.
Steps
- Split
numinto four digits: thousands isnum / 1000, hundreds is(num % 1000) / 100, tens is(num % 100) / 10, and ones isnum % 10. - Look up the thousands digit in a 4-entry list of
"",M,MM,MMM. - Look up the hundreds, tens and ones digits in their own 10-entry lists.
- Concatenate the four strings in order and return the result.
Dry run
Split 3999 into thousands = 3, hundreds = 9, tens = 9 and ones = 9.
thousands[3]isMMM.hundreds[9]isCM.tens[9]isXC.ones[9]isIX.
Join them in order: MMM + CM + XC + IX gives MMMCMXCIX, which matches the expected output.
Complexity
| Time | O(1) here, O(log n) in general |
|---|---|
| Space | O(1) auxiliary |
Let n be the value of num and d the number of decimal digits, which is at most 4 here. The code does one division or modulo and one list lookup per digit, then three string joins, so the work is proportional to d. Since d is about log10(n), the time is O(log n), which is constant for num up to 3999.
The four lists hold 34 short strings, and the output has at most 15 characters.
PythonTested in our runner
class Solution:
def intToRoman(self, num: int) -> str:
thousands = ['', 'M', 'MM', 'MMM']
hundreds = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']
tens = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC']
ones = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX']
return thousands[num // 1000] + hundreds[num % 1000 // 100] + tens[num % 100 // 10] + ones[num % 10]JavaTested in our runner
class Solution {
public String intToRoman(int num) {
String[] thousands = {"", "M", "MM", "MMM"};
String[] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
String[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
String[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return thousands[num / 1000] + hundreds[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];
}
}C++Tested in our runner
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string intToRoman(int num) {
const string thousands[] = {"", "M", "MM", "MMM"};
const string hundreds[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
const string tens[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
const string ones[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return thousands[num / 1000] + hundreds[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];
}
};JavaScriptTested in our runner
var intToRoman = function(num) {
const thousands = ['', 'M', 'MM', 'MMM'];
const hundreds = ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'];
const tens = ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'];
const ones = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'];
return thousands[Math.floor(num / 1000)] + hundreds[Math.floor((num % 1000) / 100)] + tens[Math.floor((num % 100) / 10)] + ones[num % 10];
};GoTested in our runner
func intToRoman(num int) string {
thousands := []string{"", "M", "MM", "MMM"}
hundreds := []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
tens := []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
ones := []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
return thousands[num/1000] + hundreds[(num%1000)/100] + tens[(num%100)/10] + ones[num%10]
}C#Tested in our runner
public class Solution {
public string intToRoman(int num) {
string[] thousands = {"", "M", "MM", "MMM"};
string[] hundreds = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
string[] tens = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
string[] ones = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
return thousands[num / 1000] + hundreds[(num % 1000) / 100] + tens[(num % 100) / 10] + ones[num % 10];
}
}The Integer and Roman Conversion infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Integer and Roman Conversion
Part of String Manipulation Patterns
Approach 2: Greedy over value-symbol pairsOptimalInteger and Roman Conversion
What's slow: the per-digit approach keeps four separate tables, and the six subtractive cases are spread across those tables. Each place must be indexed and joined by hand, so the code grows whenever the rules change.
The insight that fixes it: the whole numeral is one walk over 13 chunks in descending order. Take the largest chunk that fits, subtract it, and repeat. The per-place split disappears, and the subtractive pairs become ordinary entries in the table.
Why it is correct. After the loop finishes with a pair of value v, the remainder is less than v, so no later step needs that pair again. Every pair the loop skips is larger than the remainder at that moment, so it could never fit and skipping it loses nothing. Because the 13 values are exactly the pieces standard notation uses, a remainder below v is always writable with the smaller pairs, so greedy ends at exactly 0.
Steps
- Build 13 value-symbol pairs in descending order: 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.
- Start with an empty result and the input
num. - For each pair in order, while
numis at least the value, append the symbol and subtract the value fromnum. - When the loop ends,
numis 0. Return the result.
Dry run
The table below traces num = 3999. Each row is one pair in the table, read from top to bottom.
| Step | Pair (value) | num before | Action | num after | result |
|---|---|---|---|---|---|
| 1 | M (1000) | 3999 | take 3 times | 999 | MMM |
| 2 | CM (900) | 999 | take once | 99 | MMMCM |
| 3 | D (500) | 99 | skip | 99 | MMMCM |
| 4 | CD (400) | 99 | skip | 99 | MMMCM |
| 5 | C (100) | 99 | skip | 99 | MMMCM |
| 6 | XC (90) | 99 | take once | 9 | MMMCMXC |
| 7 | L (50) | 9 | skip | 9 | MMMCMXC |
| 8 | XL (40) | 9 | skip | 9 | MMMCMXC |
| 9 | X (10) | 9 | skip | 9 | MMMCMXC |
| 10 | IX (9) | 9 | take once | 0 | MMMCMXCIX |
| 11 | V (5) | 0 | skip | 0 | MMMCMXCIX |
| 12 | IV (4) | 0 | skip | 0 | MMMCMXCIX |
| 13 | I (1) | 0 | skip | 0 | MMMCMXCIX |
The loop ends with num = 0 and the result MMMCMXCIX.
Complexity
| Time | O(1) here, O(log n) in general |
|---|---|
| Space | O(1) auxiliary |
Let n be the value of num. The outer loop always visits all 13 pairs, so it does 13 checks no matter the input. The inner while loop runs once for each symbol appended, and the output has at most 4 symbols per decimal place, so the total is at most 15 appends for num up to 3999.
That makes the work constant here, and O(log n) in general because the output length grows with the digit count. The extra space is the 13-entry table plus the result, which is the answer itself, so the auxiliary space is O(1).
PythonTested in our runner
class Solution:
def intToRoman(self, num: int) -> str:
# Descending order matters: subtractive pairs must sit before their larger neighbours
value_map = [(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')]
result = []
for value, symbol in value_map:
# Take this pair as many times as it fits
while num >= value:
result.append(symbol)
num -= value
return ''.join(result)JavaTested in our runner
class Solution {
public String intToRoman(int num) {
// Descending order matters: subtractive pairs must sit before their larger neighbours
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < values.length; i++) {
// Take this pair as many times as it fits
while (num >= values[i]) {
sb.append(symbols[i]);
num -= values[i];
}
}
return sb.toString();
}
}C++Tested in our runner
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string intToRoman(int num) {
// Descending order matters: subtractive pairs must sit before their larger neighbours
const vector<pair<int, string>> table = {
{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"}
};
string result;
for (const auto& p : table) {
// Take this pair as many times as it fits
while (num >= p.first) {
result += p.second;
num -= p.first;
}
}
return result;
}
};JavaScriptTested in our runner
var intToRoman = function(num) {
// Descending order matters: subtractive pairs must sit before their larger neighbours
const table = [[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']];
let result = '';
for (const [value, symbol] of table) {
// Take this pair as many times as it fits
while (num >= value) {
result += symbol;
num -= value;
}
}
return result;
};GoTested in our runner
func intToRoman(num int) string {
// Descending order matters: subtractive pairs must sit before their larger neighbours
values := []int{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}
symbols := []string{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
result := ""
for i, v := range values {
// Take this pair as many times as it fits
for num >= v {
result += symbols[i]
num -= v
}
}
return result
}C#Tested in our runner
public class Solution {
public string intToRoman(int num) {
// Descending order matters: subtractive pairs must sit before their larger neighbours
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
var sb = new System.Text.StringBuilder();
for (int i = 0; i < values.Length; i++) {
// Take this pair as many times as it fits
while (num >= values[i]) {
sb.Append(symbols[i]);
num -= values[i];
}
}
return sb.ToString();
}
}Common mistakes
- Using
if num >= valuewhere the loop needswhile num >= value. Each symbol is then taken at most once, so 3000 becomes onlyM. Wrap the append and subtract in a loop. - Listing
(1, "I")before(4, "IV")in the table. The greedy takesIfour times and producesIIII. Keep the table in strictly descending order of value. - Leaving out the six subtractive pairs. Without
CM, 900 becomesDCCCC, and withoutIX, 9 becomesVIIII. Add all six pairs to the table. - Writing
hundreds[num / 100]without the% 10. For 1994,num / 100is 19, which is out of range for a 10-entry list. Take the digit with(num % 1000) / 100. - Storing the greedy table in an unordered container such as C++
unordered_mapor JavaHashMap. Their iteration order is not the descending order the loop needs. Use an ordered list of pairs instead.
Edge cases
num = 1returns"I", the smallest valid input.num = 4returns"IV", not"IIII", so the subtractive pair must be in the table.num = 40returns"XL", which checks the tens subtractive pair on its own.num = 3888returns"MMMDCCCLXXXVIII", the longest output of 15 characters, with no subtraction.num = 3999returns"MMMCMXCIX", the largest valid input, where every place uses a subtractive pair except thousands.
Follow-ups interviewers ask
- What if num could go above 3999?
- Standard notation stops at 3999 because M is the largest symbol. Larger values need extra notation, such as an overline that multiplies a symbol by 1000. Add those pairs to the table in descending order, and the same greedy loop still works. The output then grows with the number of digits.
- Can you do it in O(1) extra space?
- Yes, the solution already uses O(1) extra space. The table has a fixed size, and the result string is the answer itself, so it is not extra memory. For num up to 3999 the output has at most 15 characters.
- How would you convert a Roman numeral back to an integer?
- Scan the string from left to right and add each symbol's value. If a symbol is smaller than the symbol after it, subtract its value instead. This covers
IV,IXand the other four subtractive pairs, and it is LeetCode 13.
Integer to Roman FAQ
What is the time complexity of Integer to Roman?
For num up to 3999 the time is O(1), because the table has 13 entries and the output has at most 15 symbols. In general the time is O(log n), since the output has at most 4 symbols per decimal place. The per-digit version also runs in O(log n).
Why use a greedy approach for Integer to Roman?
The standard numeral is built by taking the largest chunk that fits, then repeating on the remainder. Each choice is final, so the loop never has to undo work. Because the table includes the subtractive pairs, no lookahead is needed.
Can Integer to Roman be solved in O(1) extra space?
Yes. The table size is fixed, and the result string is the answer itself. The extra memory does not depend on num, and the output is at most 15 characters for num up to 3999.
Why does 4 become IV and not IIII?
Standard Roman notation writes 4, 9, 40, 90, 400 and 900 with subtraction. The form IIII is not used in the standard system. A table that includes the pair IV produces the correct form directly.
Why does the table order matter in Python, Java and C++?
The greedy loop must visit values from largest to smallest. A Python list keeps its order, but C++ unordered_map and Java HashMap do not guarantee any order. Store the pairs in an ordered list in every language.
Asked at
See which companies ask this — Pro
Related problems
- String to Integer (atoi) · same technique: Integer and Roman Conversion
- Roman to Integer · same technique: Integer and Roman Conversion
- Excel Sheet Column Title · same technique: Integer and Roman Conversion
- Find Beautiful Indices in the Given Array II · next harder, same pattern
- Group Anagrams · same pattern: String Manipulation Patterns
- Multiply Strings · same pattern: String Manipulation Patterns
- Repeated String Match · same pattern: String Manipulation Patterns
- Shortest Palindrome · same pattern: String Manipulation Patterns
- Valid Anagram · same pattern: String Manipulation Patterns
- Valid Palindrome · same pattern: String Manipulation Patterns