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