Leet Code - Roman Numeral to Integer Function in JavaScript

anuj8126

Anuj Srivastav

Posted on July 15, 2022

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.

💖 💪 🙅 🚩
anuj8126
Anuj Srivastav

Posted on July 15, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Math Object Cheatsheet
javascript JavaScript Math Object Cheatsheet

November 25, 2024

Human-Readable JavaScript
javascript Human-Readable JavaScript

November 20, 2024

CyroScript Weekly Digest: Nov 15, 2024
javascript CyroScript Weekly Digest: Nov 15, 2024

November 16, 2024