Skip to content

Instantly share code, notes, and snippets.

@acrookston
Created May 9, 2017 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acrookston/3fd7aee49b2a542c303a5022805fcc76 to your computer and use it in GitHub Desktop.
Save acrookston/3fd7aee49b2a542c303a5022805fcc76 to your computer and use it in GitHub Desktop.
Convert roman numerals to integers
import Foundation
let values: [Character: Int] = [
"I" : 1,
"V" : 5,
"X" : 10,
"L" : 50,
"C" : 100,
"D" : 500,
"M" : 1000
]
// Translate roman literal to integer
// iterate over chars
// track total + track subtractions to next value
func roman(_ string: String) -> Int? {
var total = 0
var lastValue : Int?
for i in string.uppercased().characters {
if let current = values[i] {
if let last = lastValue {
if current > last {
total -= last
} else {
total += last
}
}
lastValue = current
} else {
return nil
}
}
total += lastValue ?? 0
return total
}
roman("x") // 10
roman("ix") // 9
roman("lxiii") // 63
roman("MCMXCIX") // 1999
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment