Preparing for the Blue Bridge Cup (Part 2)

Table of contents

Problem Description:

Parse:

code:

operation result:


Problem description :

        Roman numerals are converted to integers. Usually, the small number in Roman numerals is to the right of the large number. But there are exceptions, for example, 4 is not written as IIII, but as 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.

Parse:

        There are two situations: 1. If the number on the left is greater than the number on the right, you only need to add up the Arabic numbers corresponding to the Roman numbers.

                              2. If the number on the left is smaller than the number on the right, then the decimal must be subtracted from the large number.

code:

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

operation result:

Guess you like

Origin blog.csdn.net/h1998040218/article/details/129803885