美文网首页
13. 罗马数字转整数 LeetCode

13. 罗马数字转整数 LeetCode

作者: 出来遛狗了 | 来源:发表于2018-11-02 10:54 被阅读4次
    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
        }
    }
    

    相关文章

      网友评论

          本文标题:13. 罗马数字转整数 LeetCode

          本文链接:https://www.haomeiwen.com/subject/pguqxqtx.html