###### tags: `Leetcode` `easy` `hash` `python` `c++`
# 13. Roman to Integer
## [題目來源:] https://leetcode.com/problems/roman-to-integer
## 題目:
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, 2 is written as II in Roman numeral, just two ones added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
* I can be placed before V (5) and X (10) to make 4 and 9.
* X can be placed before L (50) and C (100) to make 40 and 90.
* C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
## 解題想法:
數字順序 判斷當前字與其前面的字
若前面大、當前小 -> 累加
若前面小、當前大 -> 扣掉!!
## Python:
``` python=
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
#大->小 加起來 小->大:大減小
dic={'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000}
res=dic[s[0]]
for i in range(1,len(s)):
pre=dic[s[i-1]]
cur=dic[s[i]]
if pre<cur:
cur-=2*pre #減兩次 因為每個數一定會加一次
res+=cur
return res
if __name__ == '__main__':
result = Solution()
print(result.romanToInt("MXL"))
```
## C++:
``` cpp=
#include <iostream>
#include <unordered_map>
using namespace std;
class Solution
{
public:
int romanToInt(string s)
{
unordered_map<char, int> dic;
dic = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}};
int res = dic[s[0]];
for (int i = 1; i < s.size(); i++)
{
int pre = dic[s[i - 1]];
int cur = dic[s[i]];
if (pre < cur)
cur -= pre * 2;
res += cur;
}
return res;
}
};
int main()
{
Solution res;
string s = "LVIII";
cout << res.romanToInt(s) << endl;
return 0;
}
```