Skip to content

Instantly share code, notes, and snippets.

@stulevine
Created February 25, 2017 12:47
Show Gist options
  • Save stulevine/c0d369bcfd623fbe9fa6f7b82a212ee2 to your computer and use it in GitHub Desktop.
Save stulevine/c0d369bcfd623fbe9fa6f7b82a212ee2 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
/*
* Description: a String extension to convert roman numerals to their respective integer values
* Synopsis:
* Any of the letters representing numbers in the Roman numerical system:
*
* I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1,000.
*
* In this system, a letter placed after another of greater value adds (thus XVI or xvi is 16),
* whereas a letter placed before another of greater value subtracts (thus XC or xc is 90).
*/
extension String {
func romanToInt() -> Int {
let romainNumerals: [String: Int] = ["I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000]
func intFromNumerals(numeral1: String?, numeral2: String?) -> Int {
let n1 = romainNumerals[numeral1 ?? "nil"] ?? 0
let n2 = romainNumerals[numeral2 ?? "nil"] ?? 0
if n1 < n2 {
return n2 - n1
}
else if n1 >= n2 {
return n1 + n2
}
return 0
}
let numeral = self
let maxIndex = numeral.characters.count
var total: Int = 0
var index: Int = 0
while index < maxIndex {
let c1 = String(numeral[numeral.index(numeral.startIndex, offsetBy: index)])
var c2: String? = nil
let next = index + 1
if next > maxIndex {
break
}
else if next < maxIndex {
c2 = String(numeral[numeral.index(numeral.startIndex, offsetBy: next)])
}
total += intFromNumerals(numeral1: c1, numeral2: c2)
index += 2
}
return total
}
}
print("\("DCLXVI".romanToInt())")
print("\("V".romanToInt())")
print("\("XIV".romanToInt())")
print("\("XXXIV".romanToInt())")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment