A Swift Solution


  • 0
    L
    class Solution {
        func romanToInt(s: String) -> Int {
            guard s.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0 else { return 0 }
    
            let table: [Character: Int] = ["I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000]
            var result = 0
            for index in s.characters.startIndex ..< s.characters.endIndex.predecessor() {
                let next = index.successor()
                if table[s.characters[index]] < table[s.characters[next]] {
                    result -= table[s.characters[index]] ?? 0
                } else {
                    result += table[s.characters[index]] ?? 0
                }
            }
            result += table[s.characters.last!] ?? 0
            return result
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.