Last active
April 8, 2016 17:32
-
-
Save kumo/43781a552ee2b845da6c to your computer and use it in GitHub Desktop.
Converting to Roman Numerals using an array of tuples
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
| func toRomanNumerals(number: Int) -> String? { | |
| guard number > 0 else { | |
| return nil | |
| } | |
| var remainder = number | |
| let values = [("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C",100), ("XC", 90), ("L",50), ("XL",40), ("X",10), ("IX", 9), ("V",5),("IV",4), ("I",1)] | |
| var result = "" | |
| for (romanChar, arabicValue) in values { | |
| let count = remainder / arabicValue | |
| if count == 0 { continue } | |
| for _ in 1...count | |
| { | |
| result += romanChar | |
| remainder -= arabicValue | |
| } | |
| } | |
| return result | |
| } | |
| toRomanNumerals(2014) // optional, otherwise toRomanTuple(2014)! | |
| toRomanNumerals(-3) // nil |
Author
Author
Swift 2.2 quite rightly complains about my var param, and guard is probably better than my if check.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In beta 5
1...countgives an error if the range is invalid (1...0), so now I have to check for that condition