13.jpg

    代码 :

    1. class Solution {
    2. public:
    3. int romanToInt(string s) {
    4. unordered_map<char, int> hash;
    5. hash['I'] = 1, hash['V'] = 5;
    6. hash['X'] = 10, hash['L'] = 50;
    7. hash['C'] = 100, hash['D'] = 500;
    8. hash['M'] = 1000;
    9. int res = 0;
    10. for(int i = 0; i < s.size(); i ++ ) {
    11. // IV = - 1 + 5
    12. if(i + 1 < s.size() && hash[s[i]] < hash[s[i+1]]) {
    13. res -= hash[s[i]];
    14. }
    15. else {
    16. res += hash[s[i]];
    17. }
    18. }
    19. return res;
    20. }
    21. };