问题
I am looking to take an Integer
in Swift and convert it to a Roman Numeral String
. Any ideas?
回答1:
One could write an extension on Int
, similar to the one seen below.
Please note: this code will return "" for numbers less than one. While this is probably okay in terms of Roman Numeral numbers (zero does not exist), you may want to handle this differently in your own implementation.
extension Int {
var romanNumeral: String {
var integerValue = self
var numeralString = ""
let mappingList: [(Int, String)] = [(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")]
for i in mappingList {
while (integerValue >= i.0) {
integerValue -= i.0
numeralString += i.1
}
}
return numeralString
}
}
Thanks to Kenneth Bruno for some suggestions on improving the code as well.
来源:https://stackoverflow.com/questions/36068104/convert-integer-to-roman-numeral-string-in-swift