Integer to Roman
Medium · Math & Geometry · Explanation and code example
Math - II
How it works
Since the input is constrained to 1-3999, we can precompute all possible Roman representations for each digit place (ones, tens, hundreds, thousands). Then we simply look up each digit and concatenate the results. This trades space for simplicity and speed.
Steps
- Create four arrays containing Roman representations for:
- Thousands: "", "M", "MM", "MMM"
- Hundreds: "", "C", "CC", ... "CM"
- Tens: "", "X", "XX", ... "XC"
- Ones: "", "I", "II", ... "IX"
- Extract each digit using division and modulo.
- Look up the corresponding string from each array.
- Concatenate and return the result.
Complexity
- Time complexity:
O(1) - Space complexity:
O(1)
Things to watch for
Missing Subtractive Combinations
Roman numerals use subtractive notation for 4, 9, 40, 90, 400, and 900 (IV, IX, XL, XC, CD, CM). A common mistake is only including the basic symbols (I, V, X, L, C, D, M) and trying to handle subtractive cases with complex conditional logic. The cleanest solution includes all 13 symbol-value pairs in your lookup table from the start.
Processing Values in Wrong Order
When building the Roman numeral string, you must process values from largest to smallest. Starting with smaller values or processing in random order will produce incorrect results. For example, processing 1994 by handling ones before thousands would give an invalid representation.
Incorrect Division and Modulo Logic
When computing how many times a symbol should appear, some implementations confuse the division and modulo operations. You need integer division to get the count of symbols, then modulo to get the remaining value. Mixing these up or forgetting to update the remaining number after each step leads to wrong outputs or infinite loops.
Python code example
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]
)
C++ code example
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];
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.