Integer to Roman
Given an integer, convert it to a Roman numeral. Roman numerals use seven symbols: I (1), V (5), X (10), L (50), C (100), D (500), M (1000). Subtractive notation is used for 4, 9, 40, 90, 400, and 900 (e.g., IV = 4, IX = 9).
Example 1:
Input: num = 3749
Output: "MMMDCCXLIX"
Example 2:
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3
Example 3:
Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90, IV = 4
Edge cases: Minimum value is 1. Maximum is typically 3999.
Sample Input
num = 3
Sample Output
"III"
Constraints
- 1 <= num <= 3999
Test Cases
Case 1
Args: [3]
Expected: "III"
Topics
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.