Created
May 9, 2017 00:24
-
-
Save acrookston/3fd7aee49b2a542c303a5022805fcc76 to your computer and use it in GitHub Desktop.
Convert roman numerals to integers
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
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