1. 程式人生 > >LeetCode-13. 羅馬數字轉整數

LeetCode-13. 羅馬數字轉整數

題目地址:https://leetcode-cn.com/problems/roman-to-integer/
題意:字面意思
思路:模擬即可
程式碼:

class Solution {
public:
    int romanToInt(string s) {
        map<string,int>m;
        m["I"] = 1;
        m["IV"] = 4;
        m["V"] = 5;
        m["IX"] = 9;
        m["X"] = 10;
        m["XL"] = 40;
        m["L"] = 50;
        m["XC"] = 90;
        m["C"] = 100;
        m["CD"] = 400;
        m["D"] = 500;
        m["CM"] = 900;
        m["M"] = 1000;
        int length = s.length();
        int sum = 0;
        for(int i=0;i<length;i++){
            if(m.count(s.substr(i,2))){
                sum += m[s.substr(i,2)];
                i++;
            }else
                sum += m[s.substr(i,1)];
        }
        return sum;
    }
};