Algorithm
for decimal number X
- Create a Object for each symbol as key and it's respective value
const roman = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
};
find the highest decimal value V that is less than or
equal to the decimal number X.Store the Roman numeral that you found after Subtracting
it's value V from X
X = X - V
Repeat above Process until you get zero of X
Example
X = 36
Javascript Function to Covert Integer to Roman Numeral
/**
* @param {number} num
* @return {string}
*/
const roman = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1
};
var intToRoman = function(num,result=[]) {
if(num == 0){
return ''
}
for(const props in roman){
if(roman[props]<=num){
result.push(props);
num = num - roman[props];
intToRoman(num,result);
return result.join("");
}
}
};
console.log(intToRoman(36));
Test Cases :
Input: num = 3
Output: "III"
Explanation: 3 is represented as 3 ones.
Input: num = 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Input: num = 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Top comments (5)
Nice :)
Have you written a function to convert back from a roman numeral string to an integer?
yes Dave , you can visit dev.to/anuj8126/leet-code-roman-nu...
Good Job
thanks for appreciation
Thanks Luke for your suggestions , it's really helpful