DEV Community

Cover image for Leet Code - Integer to Roman Numeral Function in JavaScript
Anuj Srivastav
Anuj Srivastav

Posted on • Updated on

Leet Code - Integer to Roman Numeral Function in JavaScript

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
  };
Enter fullscreen mode Exit fullscreen mode
  • 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

Image description

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));
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
neohed profile image
Dave

Nice :)

Have you written a function to convert back from a roman numeral string to an integer?

Collapse
 
anuj8126 profile image
Anuj Srivastav • Edited

yes Dave , you can visit dev.to/anuj8126/leet-code-roman-nu...

Collapse
 
samirssh profile image
kaiii0x1

Good Job

Collapse
 
anuj8126 profile image
Anuj Srivastav

thanks for appreciation

Collapse
 
anuj8126 profile image
Anuj Srivastav

Thanks Luke for your suggestions , it's really helpful