-
-
Save geek1706/5ae9523896ab3a0ded23da54915d663b to your computer and use it in GitHub Desktop.
A simple roman numerals converter in Swift
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
import Foundation | |
func toRoman(number: Int) -> String { | |
guard number < 1000 else { fatalError("Number must be less than 1000") } | |
let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] | |
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] | |
var romanValue = "" | |
var startingValue = number | |
for (index, romanChar) in romanValues.enumerated() { | |
var arabicValue = arabicValues[index] | |
var div = startingValue / arabicValue | |
if (div > 0) | |
{ | |
for j in 0..<div | |
{ | |
//println("Should add \(romanChar) to string") | |
romanValue += romanChar | |
} | |
startingValue -= arabicValue * div | |
} | |
} | |
return romanValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment