Convert Integer to Roman Numeral String in Swift

匆匆过客 提交于 2020-02-26 04:04:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!