Skip to content

Instantly share code, notes, and snippets.

@kumo
Last active February 21, 2022 21:07
Show Gist options
  • Save kumo/a8e1cb1f4b7cff1548c7 to your computer and use it in GitHub Desktop.
Save kumo/a8e1cb1f4b7cff1548c7 to your computer and use it in GitHub Desktop.
A simple roman numerals converter in Swift
// Playground - noun: a place where people can play
import Foundation
func toRoman(number: Int) -> String {
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 enumerate(romanValues) {
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
}
toRoman(2014)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment