---
# System prepended metadata

title: 13. Roman to Integer
tags: [JavaScript, Hash Map/Set, Easy, Grind 75, important]

---

思考:
![](https://hackmd.io/_uploads/BJFyPlf1a.png)

一般是 由大到小
如果有一個組合是 小大 則代表是特殊組合 EX: CM = 900 要扣掉100

```c++=
class Solution {
public:
    int romanToInt(string s) {
        unordered_map <char, int> hash;
        hash['I'] = 1;
        hash['V'] = 5;
        hash['X'] = 10;
        hash['L'] = 50;
        hash['C'] = 100;
        hash['D'] = 500;
        hash['M'] = 1000;
        int ans = 0;
        for(int i = 0; i < s.size(); i++){
            if(hash[s[i]] < hash[s[i+1]] ){
                ans -= hash[s[i]];
            }else{
                ans += hash[s[i]];
            }
        }
        return ans;

    }
};

```


```=
/**
 * @param {string} s
 * @return {number}
 */
var romanToInt = function(s) {
    const roman = {
        'I' : 1,
        'V' : 5,
        'X' : 10,
        'L' : 50,
        'C' : 100,
        'D' : 500,
        'M' : 1000
    }
    let ans = 0;
    for(let i = 0; i < s.length; i++){
        if( (i+1) < s.length && roman[s[i]] < roman[s[i+1]] ){
            ans -= roman[s[i]];
        }else{
            ans += roman[s[i]];
        }
    }

    return ans;
};

```