DEV Community

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

Posted on • Edited on

Leet Code - Roman Numeral to Integer Function in JavaScript

Algorithm

  • Create a Object for each symbol as key and it's respective
    value
    const romanobj = {
    I : 1,
    V : 5,
    X : 10,
    L : 50,
    C : 100,
    D : 500,
    M : 1000
    }

  • Split the Roman Numeral string into Roman Symbols or in different word split string into Characters.

  • Take a Symbol from Starting from 0 index
    1). If current value of symbol is greater than or equal to
    the value of next symbol, then add this value to the
    total.
    2). else subtract this value by adding the value of next
    symbol to the total.

Javascript Function to Covert Roman Numeral to Integer

/**
 * @param {string} s
 * @return {number}
 */
const obj = {
I      :     1,
V      :     5,
X      :     10,
L      :     50,
C      :     100,
D      :     500,
M      :     1000
}
var romanToInt = function(s) {
let result = 0;
for(let i=0;i<s.length;i++){
if(i+1<s.length){
if(obj[s[i]]>=obj[s[i+1]]){
 result = result + obj[s[i]];

}else{
 result = result + obj[s[i+1]]-obj[s[i]];
i++;
 } 
}else{
result = result + obj[s[i]];
}
}
return result;

};
Enter fullscreen mode Exit fullscreen mode

Test Cases

Input: s = "III"
Output: 3
Explanation: III = 3.

Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

Top comments (1)

Collapse
 
dannyengelman profile image
Danny Engelman • Edited

We are so used to reading from Left to Right, we overlook the Right to Left alternatives.

The whole point of Roman notation is you want to check if I becomes before X

That is much easier when you reverse the Roman string.

Or in JavaScript, use the hardly ever used reduceRight method

(code optimized for best GZIP/Brotli compression)