LeetCode #12: Integer to Roman
Convert an integer to its Roman numeral representation using a greedy approach.
🏛️ What Are Roman Numerals?
Roman numerals use letters to represent values:
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000
IV = 4
(5 - 1)IX = 9
(10 - 1)XL = 40
(50 - 10)XC = 90
(100 - 10)CD = 400
(500 - 100)CM = 900
(1000 - 100)
The key: represent numbers by combining symbols, using subtractive notation for 4, 9, 40, etc.
The Problem
Given an integer between 1
and 3999
, convert it to a Roman numeral string.
Examples
Input: 3 → Output: III
(1 + 1 + 1)
Input: 4 → Output: IV
(5 - 1)
Input: 9 → Output: IX
(10 - 1)
Input: 58 → Output: LVIII
(50 + 5 + 1 + 1 + 1)
Input: 1994 → Output: MCMXCIV
(1000 (M) + 900 (CM) + 90 (XC) + 4 (IV))
✅ Algorithm: Greedy Matching
We use a greedy approach: always use the largest possible symbol first.
- Create a list of values and their Roman symbols (including subtractive cases)
- Sort them in descending order
- While the number > 0, subtract the largest possible value and append its symbol
- Repeat until the number is 0
Solution (JavaScript)
function intToRoman(num) {
const values = [
1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
];
const symbols = [
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"
];
let result = "";
for (let i = 0; i < values.length; i++) {
const value = values[i];
const symbol = symbols[i];
while (num >= value) {
result += symbol;
num -= value;
}
}
return result;
}
🧠 Why Greedy Works
Because Roman numerals are designed with decreasing values, we can always safely use the largest symbol possible.
Example: For 1994
:
- Use
M
(1000) → 994 left - Use
CM
(900) → 94 left - Use
XC
(90) → 4 left - Use
IV
(4) → 0 left
Result: MCMXCIV
🎮 Try It: Roman Numeral Builder
Watch how each symbol is added step by step.
Roman Numeral Visualizer
Watch each symbol get added
M
(1000)🌍 Real-World Applications
Roman numerals aren't just ancient history — they're still used today.
📅 Clocks & Watches
Many analog clocks use Roman numerals for a classic look.
🎬 Movie Release Years
Films often show the copyright year in Roman numerals (e.g., "MMXXIV").
📚 Book Chapters & Outlines
Used in prefaces, outlines, and legal documents for hierarchical numbering.
🎮 Game Levels
"Level IV" sounds more epic than "Level 4" — great for fantasy or historical games.
💡 Fun Fact: The Romans had no symbol for zero — which made math much harder! Our modern number system came from India and Arabia.
Summary
The specific algorithm solves a narrow problem, but the greedy technique it demonstrates is useful in coin change, symbolic encoding, and resource allocation problems.