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

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

Β·

2 min read

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.

Solution

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;
            i++;
        } else {
            result += firstSymbolValue;
        }
    }

    return result;
};

πŸ‘‰ Support me: buymeacoffee.com/abusalehfaysal

πŸ‘‰ YouTube Video Link: youtu.be/c081jEHzsvo

πŸ‘‰ YouTube Channel: youtube.com/channel/UCW_09Nbobf4URLkAlEo84sw

πŸ‘‰ PlayList Link: youtube.com/playlist?list=PLUnklBXn8NSefCpB..

πŸ‘‰ Connect with me (LinkedIn): linkedin.com/in/abusalehfaysal

πŸ‘‰ Follow our LinkedIn Page: linkedin.com/company/thebacklogprogrammer

πŸ‘‰ Like our Facebook page: facebook.com/thebacklogprogrammer

πŸ‘‰ Join our community (Facebook group): facebook.com/groups/5500588936676942

πŸ‘‰ Follow me at: facebook.com/AbuSalehFaysal10

πŸ‘‰ Twitter: twitter.com/AbuSalehFaysal

πŸ‘‰ Abu Saleh Faysal’s Blog: abusalehfaysal.hashnode.dev

πŸ‘‰ Hasnode: hashnode.com/@AbuSalehFaysal

πŸ‘‰ Dev Community: dev.to/abusalehfaysal

πŸ‘‰ freeCodeCamp: freecodecamp.org/abusalehfaysal

πŸ‘‰ Medium: abusalehfaysal.medium.com

πŸ‘‰ GitHub: github.com/AbuSalehFaysal

πŸ‘‰ GitLab: gitlab.com/AbuSalehFaysal

Β