Solution in Swift


  • 0
    J
    class Solution {
        func romanToInt(_ s: String) -> Int {
            let reversed = s.characters.reversed()
            let values = ["I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000]
            var lastValue = 0
            var result = 0
            for c in reversed {
                let value = values[String(c)]!
                if value < lastValue {
                    result -= value
                } else {
                    result += value
                }
                lastValue = value
            }
            return result
        }
    }
    

Log in to reply
 

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