> For the complete documentation index, see [llms.txt](https://cai-sen-se.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cai-sen-se.gitbook.io/leetcode/1-200/13.-luo-ma-shu-zi-zhuan-zheng-shu.md).

# 13. 罗马数字转整数

<https://leetcode-cn.com/problems/roman-to-integer/>

## 解法一：左加右减

这个思路很6，根据罗马数字的**左加右减**法则，比较s\[i]和s\[i+1]所表示的数字大小，若s\[i]\<s\[i+1]，则res减去s\[i]，否则res加上s\[i]

```python
class Solution:
    def romanToInt(self, s: str) -> int:
        #符号映射到数字
        dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        res = 0
        for i in range(len(s)):
            if i+1 < len(s) and dict[s[i]] < dict[s[i+1]]:
                res -= dict[s[i]]
            else:
                res += dict[s[i]]
        return res
```

先将s转换成相应数字，再比较，省去了查dict的时间，速度更快

```python
class Solution:
    def romanToInt(self, s: str) -> int:
        dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        nums = [0] * len(s)
        for i in range(len(s)):    #转换成数字
            nums[i] = dict[s[i]]
        res = 0
        for i in range(len(s)):
            if i+1 < len(s) and nums[i] < nums[i+1]:
                res -= nums[i]
            else:
                res += nums[i]
        return res
```
