Submission link - https://bigfrontend.dev/problem/roman-numerals-to-integer/discuss/650
/**
* @param {string} str - roman numeral string
* @returns {number} integer
*/
function romanToInteger(str) {
// keep value of 7 symbols
const symbolMapper = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
};
// we will keep adding/substracting number based on condition
// so we need to begin with 0
let result = 0;
// iterate over the string to convert it to the number
for(let i =0; i < str.length; i++) {
const symbolValue = symbolMapper[str.charAt(i)]; // first char value
const nextSymbolValue = symbolMapper[str.charAt(i+1)]; // next char value
const lastChar = str.length - 1; // last char (there is no next char when we hit last char)
// as per rule describe in problem
// there is no next char to compare when we hit last char so we just add it
if((symbolValue >= nextSymbolValue) || (i == lastChar)) {
result += symbolValue;
} else {
result -= symbolValue;
}
}
return result;
}
The algorithm is already given in the problem so it was easy to solve this problem.
Symbols are listed from highest to lowest, from left to right
- If the next symbol value is bigger than the current one, it means subtracting, otherwise adding.
- As roman numbers have only 7 symbols, we will keep them with their corresponding values in an Object. Feel free to use a fancy Map or Set.
- We will declare a
result
variable with an initial value of0
- Why
0
? Because we need to subtract and add values based on condition. So the beginning condition must be0
.
- Why
- We will loop over the roman string.
- We will define and declare current symbol value
symbolValue
, next symbol valuenextSymbolValue
and also keep last charlastChar
- As per the algorithm, we check if
symbolValue
>=nextSymbolValue
then we willsymbolValue
in the result - Else we will subtract from the
result
- In case, we hit last char in roman string and there is nothing to compare then we add
lastChar
symbol value - We finally return the
result
I'm excited to improve the solution and code walkthrough. Feel free to drop a comment, or send a PR or send memes @knowkalpesh.