Integer to Roman
Translate an integer into its Roman numeral form. The Roman numeral system is built from seven base symbols โ I (1), V (5), X (10), L (50), C (100), D (500), and M (1000) โ combined by addition, except for six special cases (4, 9, 40, 90, 400, 900) where a smaller symbol placed before a larger one means subtraction instead (so IV reads as 4 and IX as 9).
Edge cases: Minimum value is 1. Maximum is 3999.
Sample Input and Output
Example 1 ยท Run Sample
num = 3 "III" Example 2
num = 1994 "MCMXCIV" - 1 <= num <= 3999
Test Cases (2)
Approach: Greedy with Value Table
Map all 13 Roman symbols (including the six subtractive forms) to their values in descending order. Greedily subtract the largest possible value and append the corresponding symbol until the number reaches zero.
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++) {
while (num >= values[i]) {
result += symbols[i];
num -= values[i];
}
}
return result;
}Time Complexity: O(1) โ bounded by the fixed set of symbols (at most ~15 iterations)
Space Complexity: O(1)
Saved in this browser only. Private to you.