Last active
September 16, 2019 00:00
-
-
Save jakehawken/2c8c87890f7d7b23e0e7631c7f0ca0d4 to your computer and use it in GitHub Desktop.
Leetcode #13: Converts a number in roman numerals to an Integer. Assumes a valid roman numeral.
This file contains hidden or 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
| let romanMapping: [String: Int] = [ | |
| "I" : 1, | |
| "V" : 5, | |
| "X" : 10, | |
| "L" : 50, | |
| "C" : 100, | |
| "D" : 500, | |
| "M" : 1000 | |
| ] | |
| func romanToInt(_ s: String) -> Int { | |
| var output = 0 | |
| var lastCharStr = "" | |
| for character in s { | |
| let currenCharStr = String(character) | |
| guard let currentVal = romanMapping[currenCharStr] else { | |
| lastCharStr = "" | |
| continue | |
| } | |
| if let lastVal = romanMapping[lastCharStr] { | |
| if currentVal/10 == lastVal { | |
| let toAdd = currentVal - (lastVal * 2) | |
| output += toAdd | |
| } | |
| else if currentVal/5 == lastVal { | |
| let toAdd = currentVal - (lastVal * 2) | |
| output += toAdd | |
| } | |
| else { | |
| output += currentVal | |
| } | |
| } | |
| else { | |
| output += currentVal | |
| } | |
| lastCharStr = currenCharStr | |
| } | |
| return output | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment