Created
February 15, 2025 15:41
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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