Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Created February 15, 2025 15:41
Show Gist options
  • Save primaryobjects/e35354d55e59f9eb0b115747f0cc1826 to your computer and use it in GitHub Desktop.
Save primaryobjects/e35354d55e59f9eb0b115747f0cc1826 to your computer and use it in GitHub Desktop.
Convert roman numeral to integer in javascript. https://leetcode.com/problems/roman-to-integer/
function romanToInt(s: string): number {
let result = 0;
const symbols = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
};
let lastValue: number = null;
for (let i: number = s.length - 1; i >= 0; i--)
{
const symbol: string = s[i];
const value: number = symbols[symbol];
// Account for the current symbol being less than the prior signifying -value: IV, IX, etc.
if (lastValue && lastValue > value) {
result -= value;
}
else {
result += value;
}
lastValue = value;
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment