Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active June 2, 2016 11:40
Show Gist options
  • Select an option

  • Save kristopherjohnson/ac7a42d0a4c2ae041083ffa3a1b52a79 to your computer and use it in GitHub Desktop.

Select an option

Save kristopherjohnson/ac7a42d0a4c2ae041083ffa3a1b52a79 to your computer and use it in GitHub Desktop.
Swift: Generate Roman numerals
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