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.

算法

Hash表进行转换表的模拟

C++代码

class Solution {
public:
    /*
    题意: 将罗马数字转换成int
    按照转换表模拟即可
    */
    int romanToInt(string s) {
        unordered_map<char, int> num;
        num['I'] = 1;
        num['V'] = 5;
        num['X'] = 10;
        num['L'] = 50;
        num['C'] = 100;
        num['D'] = 500;
        num['M'] = 1000;
        int ans = num[s[s.length() - 1]];
        for (int i = s.length() - 2; i >= 0; i--) {
            if (num[s[i]] < num[s[i + 1]])
                ans -= num[s[i]];
            else
                ans += num[s[i]];
        }
        return ans;
    }
};

Bug Free Procedure 从记事本直接写代码

2016.12.13 算法错误