[LeetCode] 13. Roman to Integer

Given a roman numeral, convert it to an integer.

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

Analyse:

//• I 代表 1

//• V 代表 5

//• X 代表 10

//• L 代表 50

//• C 代表 100

//• D 代表 500

//• M 代表 1000

/*ex:

I -> 1

II -> 2

III -> 3

// 但這種會比較特殊

IV -> 4

// 當小數字在大數字的前面時,變成大數字減小數字

// 繼續下去

V -> 5

VI -> 6

VII -> 7

VIII -> 8

// 又遇到一個,所以是 10 - 1

IX -> 9

/* ex:

例如 XLIX ->

X -> 答案 = 10

// L 符合規則二 (L > X)

L -> 答案 = 10 + (50 - 2*10)

I -> 答案 = 10 + 30 + 1

// X 符合規則二 (X > I)

X -> 答案 = 10 + 30 + 1 + (10 - 2*1)

-> 答案 = 10 + 30 + 1 + 8 = 49

*/

Solution:

class Solution {
    func romanToInt(_ s: String) -> Int {
        let list: [String: Int] = ["I": 1, "V": 5, "X" : 10, "L": 50, "C": 100, "D": 500, "M": 1000]
    
        var output = 0
        let chars = Array(s)
        var lastValue = 0
        
        for i in 0..<chars.count {
            
            let char = String(chars[i])
            let value = list[char]!
            if (value > lastValue) {
                output = output + value - 2 * lastValue
            } else {
                output = output + value
            }
            
            lastValue = value
        }       

        return output
    }   
}

Last updated