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
}
}
}