Last active
August 29, 2015 14:11
-
-
Save hooman/1c8c2352ccff95177551 to your computer and use it in GitHub Desktop.
One of my Swift samples for RosettaCode.org
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
func intToRoman(var n: Int) -> String { | |
var result = "" | |
for (value, letter) in | |
[( 1000, "M"), | |
( 900, "CM"), | |
( 500, "D"), | |
( 400, "CD"), | |
( 100, "C"), | |
( 90, "XC"), | |
( 50, "L"), | |
( 40, "XL"), | |
( 10, "X"), | |
( 9, "IX"), | |
( 5, "V"), | |
( 4, "IV"), | |
( 1, "I")] | |
{ | |
while n >= value { | |
result += letter | |
n -= value | |
} | |
} | |
return result | |
} | |
println(intToRoman(1666)) // MDCLXVI | |
// This function does not validate the string. | |
func romanToInt(var str: String) -> Int { | |
var result = 0 | |
for (value, letter) in | |
[( 1000, "M"), | |
( 900, "CM"), | |
( 500, "D"), | |
( 400, "CD"), | |
( 100, "C"), | |
( 90, "XC"), | |
( 50, "L"), | |
( 40, "XL"), | |
( 10, "X"), | |
( 9, "IX"), | |
( 5, "V"), | |
( 4, "IV"), | |
( 1, "I")] | |
{ | |
while str.hasPrefix(letter) { | |
result += value | |
str = str[advance(str.startIndex, countElements(letter)) ..< str.endIndex] | |
} | |
} | |
return result | |
} | |
println(romanToInt("MDCLXVI")) // 1666 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment