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.

## 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;
};

π Abu Saleh Faysalβs Blog: https://abusalehfaysal.hashnode.dev/
π Hasnode: https://hashnode.com/@AbuSalehFaysal
π Dev Community: https://dev.to/abusalehfaysal
π freeCodeCamp: https://www.freecodecamp.org/abusalehfaysal
π Medium: https://abusalehfaysal.medium.com/

π GitHub: https://github.com/AbuSalehFaysal
π GitLab: https://gitlab.com/AbuSalehFaysal