Skip to content

Instantly share code, notes, and snippets.

@frankchang0125
Last active September 9, 2018 11:59
Show Gist options
  • Save frankchang0125/8eccc708696ced3d85a50cc6017fd1ce to your computer and use it in GitHub Desktop.
Save frankchang0125/8eccc708696ced3d85a50cc6017fd1ce to your computer and use it in GitHub Desktop.
13. Roman to Integer
func romanToInt(s string) int {
sum := 0
var prev string
for i := len(s) - 1; i >= 0; i-- {
c := string(s[i])
switch c {
case "I":
if prev == "V" || prev == "X" {
sum -= 1
} else {
sum += 1
}
case "V":
sum += 5
case "X":
if prev == "L" || prev == "C" {
sum -= 10
} else {
sum += 10
}
case "L":
sum += 50
case "C":
if prev == "D" || prev == "M" {
sum -= 100
} else {
sum += 100
}
case "D":
sum += 500
case "M":
sum += 1000
}
prev = c
}
return sum
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment