Skip to content

Instantly share code, notes, and snippets.

@arbaz52
Created May 9, 2021 11:02
Show Gist options
  • Save arbaz52/08a1e59ebd6b20ff03aee50472549620 to your computer and use it in GitHub Desktop.
Save arbaz52/08a1e59ebd6b20ff03aee50472549620 to your computer and use it in GitHub Desktop.
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