LeetCode — Roman to Integer
Apr 16, 2025
I like to paste my LeetCode solutions here. It gives me a sense of progress, and it helps me achieve my goal of writing a blog daily.
Problem: https://leetcode.com/problems/roman-to-integer/
Solution — 5ms | O(n)
/**
* @param {string} s
* @return {number}
*/
var romanToInt = function(s) {
const strArr = s.split("");
const strArrLen = strArr.length;
const romanLiteralsMap = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000
};
let integerValue = 0;
for (let i = 0; i < strArrLen; i++) {
if (romanLiteralsMap[strArr[i]] < romanLiteralsMap[strArr[i + 1]]) {
integerValue += (romanLiteralsMap[strArr[i + 1]] - romanLiteralsMap[strArr[i]]);
i++;
} else {
integerValue += romanLiteralsMap[strArr[i]];
}
}
return integerValue;
};
The logic is simple. If the roman numeral is smaller than the one next to it, then subtract and skip the next numeral. Otherwise, add it up.