title: LeetCode "13. Roman to Integer" published: true description: Solution of LeetCode "13. Roman to Integer" tags: [leetcode, python]


Umm... How to remove a lot ofpos += 1 and pos < len_str

13. Roman to Integer

```python class Solution: def romanToInt(self, s: str) -> int:

    if not s:
        return 0

    pos = 0
    len_str = len(s)
    numOfDigits = 0
    symbols = ['dummy', ('I', 'V', 'X'), ('X', 'L', 'C'), ('C', 'D', 'M'), ('M')]
    s = s[::-1]
    value = 0

    while pos < len_str:
        num = 0
        numOfDigits += 1

        # ex. I ... III, VI ... VIII
        if s[pos] == symbols[numOfDigits][0]:      
            num = 1
            pos += 1
            while pos < len_str and s[pos] == symbols[numOfDigits][0]:
                num += 1
                pos += 1
            if pos < len_str and s[pos] == symbols[numOfDigits][1]:
                num += 5
                pos += 1

        # ex. V, IV
        elif s[pos] == symbols[numOfDigits][1]:
            num = 5
            pos += 1
            if pos < len_str and s[pos] == symbols[numOfDigits][0]:
                num -= 1
                pos += 1

        # ex. IX, XC, M
        elif s[pos] == symbols[numOfDigits][2]:
            num = 10
            pos += 1
            if pos < len_str and s[pos] == symbols[numOfDigits][0]:
                num -= 1
                pos += 1

        value += num * (10 ** (numOfDigits - 1))

    return value

```