Last active
June 2, 2016 11:40
-
-
Save kristopherjohnson/ac7a42d0a4c2ae041083ffa3a1b52a79 to your computer and use it in GitHub Desktop.
Swift: Generate Roman numerals
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
| private let onesSymbols = ["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"] | |
| private let tensSymbols = ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"] | |
| private let hundredsSymbols = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"] | |
| /// Generate Roman numeral representation of a value. | |
| /// | |
| /// - parameter value: Numeric value to be represented. | |
| /// - returns: `String` (possibly empty) | |
| public func romanNumeralForValue(value: Int) -> String { | |
| if value <= 0 { | |
| return "" | |
| } | |
| let ones = value % 10 | |
| let tens = (value / 10) % 10 | |
| let hundreds = (value / 100) % 10 | |
| let thousands = value / 1000 | |
| let thousandsSymbols = String(count: thousands, repeatedValue: Character("M")) | |
| return thousandsSymbols + hundredsSymbols[hundreds] + tensSymbols[tens] + onesSymbols[ones] | |
| } | |
| // Tests | |
| assert(romanNumeralForValue(0) == "") | |
| assert(romanNumeralForValue(1) == "I") | |
| assert(romanNumeralForValue(999) == "CMXCIX") | |
| assert(romanNumeralForValue(1967) == "MCMLXVII") | |
| assert(romanNumeralForValue(2016) == "MMXVI") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment