Swift Solution


  • 0
    2
    let pts = ["I" : 1, "V" : 5, "X" : 10, "L" : 50, "C" : 100, "D" : 500, "M" : 1000]
        func romanToInt(_ s: String) -> Int {
            var c = 0
            var l = 0
            var i = 0
            let chars = Array(s.characters)
            while i < s.characters.count {
                if let v = pts[String(chars[i])] {
                    if v <= l {
                        c += v
                    } else {
                        c -= l
                        c += v - l
                    }
                    l = v
                }
                i = i+1
            }
            return c
        }
    

Log in to reply
 

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