JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)
How do you convert between Roman Numerals and Integers in JavaScript?
mid LevelCode ExampleFormsPerformanceHTTP & REST APIs
Converting between Roman numerals and integers is one of the most frequently asked practical coding interview challenges.
1. Integer to Roman Numeral (intToRoman)
Using a Greedy Algorithm with a descending ordered list of Roman numeral symbols and their values (including the 6 subtractive edge cases: IV, IX, XL, XC, CD, CM):
javascript
function intToRoman(num) {
const romanMap = [
[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 [val, symbol] of romanMap) {
if (num === 0) break;
const count = Math.floor(num / val);
if (count > 0) {
result += symbol.repeat(count);
num %= val;
}
}
return result;
}
console.log(intToRoman(1994)); // "MCMXCIV" (1000=M, 900=CM, 90=XC, 4=IV)
console.log(intToRoman(58)); // "LVIII" (50=L, 8=VIII)
2. Roman Numeral to Integer (romanToInt)
Traverse the string from left to right. If the current Roman symbol has a smaller value than the next symbol, subtract it; otherwise, add it:
javascript
function romanToInt(s) {
const values = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
let total = 0;
for (let i = 0; i < s.length; i++) {
const current = values[s[i]];
const next = values[s[i + 1]];
// If a smaller value precedes a larger value, subtract it (e.g., IV = 5 - 1 = 4)
if (next && current < next) {
total -= current;
} else {
total += current;
}
}
return total;
}
console.log(romanToInt("MCMXCIV")); // 1994
console.log(romanToInt("LVIII")); // 58
Complexity Analysis:
- Time Complexity: $\mathcal{O}(1)$ — Roman numbers are constrained between $1$ and $3999$ with a maximum length of 15 characters.
- Space Complexity: $\mathcal{O}(1)$ lookup tables.