LeetCode 100 questions 13 Convert Roman numerals to integers Python3

@Leetcode

Leetcode 13. Convert Roman Numerals to Integers

topic

Roman numerals contain the following seven characters: I, V, X, L, C, D, and M.

Character value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, the Roman numeral 2 is written as II, that is, two parallel 1s. 12 written as XII is X + II. 27 is written as XXVII, which is XX + V + II.

Normally, the smaller digits in Roman numerals are to the right of the larger digits. But there are also special cases, for example, 4 is not written as IIII, but IV. The number 1 is on the left of the number 5, and the represented number is equal to the value 4 obtained by reducing the number 1 from the large number 5. Likewise, the number 9 is expressed as IX. This particular rule applies only to the following six situations:

I can be placed to the left of V (5) and X (10) to represent 4 and 9.
X can be placed to the left of L (50) and C (100) to represent 40 and 90.
C can be placed to the left of D (500) and M (1000) to represent 400 and 900.
Given a Roman numeral, convert it to an integer.

example

Input: s = "III"
Output: 3

analyze

As a special case, the character on the left of the two characters is smaller than the character on the right, and equal to the number represented by the character on the right minus the number represented by the character on the left. For example, CM is equal to 1000 - 1001000−100, XC is equal to 100 - 10100−10…

Therefore, we store char:value in Roman2Int's dictionary. Then traverse each character from left to right, if s[i] < s[i+1], subtract the number represented by s[i] from the result; otherwise, add the number represented by s[i] to the result. Remember to add the last digit at the end.

the code

class Solution:
    def romanToInt(self, s: str) -> int:
        Roman2Int = {
    
    'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        Int = 0
        n = len(s)  
        for i in range(n - 1):
            if Roman2Int[s[i]] < Roman2Int[s[i + 1]]:
                Int -= Roman2Int[s[i]]
            else:
                Int += Roman2Int[s[i]]
        return Int + Roman2Int[s[-1]]

operation result

Guess you like

Origin blog.csdn.net/weixin_45818370/article/details/123836051