image.png
class Solution {
func romanToInt(_ s: String) -> Int {
let dic = ["I" : 1,
"V" : 5,
"X" : 10,
"L" : 50,
"C" : 100,
"D" : 500,
"M" : 1000]
var arr:[String] = [];
for c in s{
arr.append(String(c));
}
var result = 0;
for i in 0..<arr.count{
if i+1 < arr.count{
if arr[i] == "I",(arr[i+1] == "V" || arr[i+1] == "X"){
result = result - dic[arr[i]]! ;
}else if arr[i] == "X",(arr[i+1] == "L" || arr[i+1] == "C"){
result = result - dic[arr[i]]! ;
}else if arr[i] == "C",(arr[i+1] == "D" || arr[i+1] == "M"){
result = result - dic[arr[i]]! ;
}else{
result = result + dic[arr[i]]!
}
}else{
result = result + dic[arr[i]]!
}
}
if result > 3999 || result < 1{
return 0
}
return result
}
}
网友评论