DEV Community

Cover image for 13. Roman to Integer - JavaScript Solution - by Abu Saleh Faysal
Abu Saleh Faysal
Abu Saleh Faysal

Posted on


13. Roman to Integer - JavaScript Solution - by Abu Saleh Faysal

Given a roman numeral, we need to convert it to an integer.

After seeing the problem, I thought that I can try with an object to store the roman symbol value and for loop to access the given string.


Step 01: Store the roman symbol value in a variable called "romanSymbolValue".
Step 02: Declare a variable called "result" and set the initial value as 0.
Step 03: Run a for loop, and identify the string symbol value, if the first character symbols value is less than the next symbols value, subtract the first value from the next value and add with the result; Then increment the index value by one.
Step 04: If there is only one character or the first character's symbol value is not less than the next character's symbol value, then, add the first character's symbol value with the result.
Step 05: Return the result.

 * @param {string} s
 * @return {number}
var romanToInt = function(s) {
    const romanSymbolValue = {
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000

    let result = 0;

    for(let i = 0; i < s.length; i++) {
        const firstSymbolValue = romanSymbolValue[s[i]];
        const secondSymbolValue = romanSymbolValue[s[i+1]];

        if(firstSymbolValue < secondSymbolValue) {
            result += secondSymbolValue - firstSymbolValue;
        } else {
            result += firstSymbolValue;

    return result;
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Support me:

πŸ‘‰ YouTube Video Link:
πŸ‘‰ YouTube Channel:
πŸ‘‰ PlayList Link:

πŸ‘‰ Connect with me (LinkedIn):
πŸ‘‰ Follow our LinkedIn Page:
πŸ‘‰ Like our Facebook page:
πŸ‘‰ Join our community (Facebook group):
πŸ‘‰ Follow me at:
πŸ‘‰ Twitter:

πŸ‘‰ Abu Saleh Faysal’s Blog:
πŸ‘‰ Hasnode:
πŸ‘‰ Dev Community:
πŸ‘‰ freeCodeCamp:
πŸ‘‰ Medium:

πŸ‘‰ GitHub:
πŸ‘‰ GitLab:

Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!