Swift LeetCode 系列之 13: roman-to-integer

https://leetcode.com/problems/roman-to-integer/description/

class Solution {
    func romanToInt(_ s: String) -> Int {
        let charcters = [Character](s)
        var result: Int = 0
        
        if let first = charcters.first { // 取第一个数字
            result = romaonCharToInt(first)
        }
        for index in 1 ..< charcters.count {
                let current = romaonCharToInt(charcters[index])
                let pre = romaonCharToInt(charcters[index - 1])
                if current <= pre {
                    result += current
                }else { //如果大于的前面的数字,我们加上当前的数字减去二倍前面的数字,这样可以把在上一个循环多加数减掉
                    result = result - pre * 2 + current;
                }
        }
        return result
    }
    
    func romaonCharToInt(_ c: Character) -> Int {
        let char = c
        switch(char) {
        case "I":
            return 1
        case "V":
            return 5
        case "X":
            return 10
        case "L":
            return 50
        case "C":
            return 100
        case "D":
            return 500
        case "M":
            return 1000
        default:
            return 0
        }
    }
    
}
    原文作者:TimberTang
    原文地址: https://www.jianshu.com/p/cdf440588989
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞