SteveSmith SteveSmith - 7 months ago 28
Swift Question

How to take a Roman Numeral String and convert it to base10 digit?

So I am building a sample project which takes roman numerals and converts it to a base10 digit. I tried getting this to work but have not accomplished my goal. Is there anyone who knows how to accomplish this? I am adding the roman numerals up to 10 below for reference. Thanks!

1 - I
2 - II
3 - III
4 - IV
5 - V
6 - VI
7 - VII
8 - VIII
9 - IX
10 - X

Answer

All you need is to iterate through your roman string characters in a reverse way and map those characters values. Start with maxValue equal to zero, if the value is greater than maxValue add it otherwise subtract and save it as the maxValue if greater than the actual value. Try like this:

extension String {
    var romanToDecimal: Int {
        var result = 0
        var maxValue = 0
        for char in uppercaseString.characters.reverse() {
            let value: Int
            switch char {
            case "M":
                value = 1000
            case "D":
                value = 500
            case "C":
                value = 100
            case "L":
                value = 50
            case "X":
                value = 10
            case "V":
                value = 5
            case "I":
                value = 1
            default:
                value = 0
            }
            maxValue = max(value, maxValue)
            result += value == maxValue ? value : -value
        }
        return result
    }
}

"MCMLXXVIII".romanToDecimal  // 1978

or as a method:

func romanToDecimal(roman:String) -> Int {
    var result = 0
    var maxValue = 0
    for char in roman.uppercaseString.characters.reverse() {
        let value: Int
        switch char {
        case "M":
            value = 1000
        case "D":
            value = 500
        case "C":
            value = 100
        case "L":
            value = 50
        case "X":
            value = 10
        case "V":
            value = 5
        case "I":
            value = 1
        default:
            value = 0
        }
        maxValue = max(value, maxValue)
        result += value == maxValue ? value : -value
    }
    return result
}
romanToDecimal("MCMLXXVIII")  // 1978