
Sponsored
Sponsored
This approach utilizes a greedy strategy by iterating over an ordered list of numeral values and corresponding symbols. Starting from the largest value, it repeatedly subtracts from the given number until the result is less, appending the equivalent symbol each time. This ensures the numeral is created with the fewest characters.
Time Complexity: O(1) — The solution has a fixed iteration through a constant list of length 13, hence it's O(1).
Space Complexity: O(1) — Uses constant space for the result string and numeral arrays.
1function intToRoman(num) {
2 const values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
3 const symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
4 let result = "";
5
6 for (let i = 0; i < values.length; i++) {
7 while (num >= values[i]) {
8 result += symbols[i];
9 num -= values[i];
10 }
11 }
12
13 return result;
14}
15
16const number = 1994;
17console.log(`Roman numeral for ${number} is ${intToRoman(number)}`);The JavaScript version accumulates characters to a result string by iterating through arrays of values and symbols and subtracting from the number until the completion of the Roman numeral transformation.