13. Roman to Integer--LeetCode Record

Tong_hdj發表於2016-07-14

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

    let record:[Character:Int] = ["M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1]
    func romanToInt(s: String) -> Int {
        var index = s.endIndex.predecessor()
        var result:Int = 0
        var preCh = s[index]

        result += record[preCh]!

        if s.characters.count > 1 {
            while index.predecessor() != s.startIndex {
                index = index.predecessor()
                result += middleResult(s[index], preCh)
                preCh = s[index]
            }
            result += middleResult(s[s.startIndex], preCh)
        }

        return result
    }

    func middleResult(p: Character, _ q: Character)->Int {
        if record[p]! < record[q]! {
            return record[p]! * -1
        }
        return record[p]!
    }

相關文章