Created
May 9, 2021 11:02
-
-
Save arbaz52/08a1e59ebd6b20ff03aee50472549620 to your computer and use it in GitHub Desktop.
For more information visit: 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
const SYMBOLS = { | |
"I": 1, | |
"V": 5, | |
"X": 10, | |
"L": 50, | |
"C": 100, | |
"D": 500, | |
"M": 1000 | |
} | |
function romanToInt(s: string): number { | |
let total = 0 | |
for(let i = 0; i < s.length; i++){ | |
const symbol = s[i] | |
let value = SYMBOLS[symbol] | |
const nextSymbol = s[i+1] | |
if(!!nextSymbol | |
&& ( | |
(symbol === "I" && (nextSymbol === "V" || nextSymbol === "X")) | |
|| (symbol === "X" && (nextSymbol === "L" || nextSymbol === "C")) | |
|| (symbol === "C" && (nextSymbol === "D" || nextSymbol === "M")) | |
) | |
) | |
value *= -1 | |
total += value | |
} | |
return total | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment