[Leetcode Brush Questions] Algorithm: Convert Roman Numerals to Integers

1. Problems

insert image description here

2. Code understanding

class Solution:
    def romanToInt(self, s: str) -> int:
        answer=0
        length = len(s)
        d={
    
    'I':1,'V':5,'X':10, 'L':50,'C':100, 'D':500,'M':1000}
        for i in range(length-1):
            if d[s[i+1]]>d[s[i]]:
                answer=answer-d[s[i]]
            else:
                answer=answer+d[s[i]]
        answer=answer+d[s[length-1]]
        return answer
  • Define a Solution class that contains a romanToInt method for converting Roman numerals to integers.
  • Initialize the variable answer to 0 to store the converted integer value.
  • Get the length of the input string s and store it in the variable length.
  • Create a dictionary d that maps each Roman numeral character to the corresponding numeric value.
  • Use a for loop to iterate through each character in s, from the first character to the second-to-last character.
  • If the numeric value of the current character is less than the numeric value of the next character, subtract the numeric value of the current character from answer.
  • Otherwise, add answer to the numeric value of the current character.
  • Add answer to the value corresponding to the last character to complete the conversion of the entire Roman numeral.
  • Return the final result answer.

The purpose of this code is to traverse the Roman numeral string s, and according to the size relationship of adjacent characters, accumulate or subtract the corresponding values ​​into answer, and finally obtain the Roman numerals in the form of integers.

The second option:

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

try again:

class Solution:
    def romanToInt(self, s: str) -> int:
        d = {
    
    
            'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000
        }
        res = 0
        prev_val = 0
        
        for c in reversed(s):
            curr_val = d[c]
            if curr_val < prev_val:
                res -= curr_val
            else:
                res += curr_val
            prev_val = curr_val
        
        return res

Last version:

class Solution:
    def romanToInt(self, s: str) -> int:
        roman_values = {
    
    
            'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000
        }
        res = 0
        prev_val = 0
        
        for c in reversed(s):
            curr_val = roman_values[c]
            if curr_val < prev_val:
                res -= curr_val
            else:
                res += curr_val
            prev_val = curr_val
        
        return res
  • Define a Solution class that contains a romanToInt method for converting Roman numerals to integers.
  • Create a dictionary roman_values ​​that maps each Roman numeral character to its corresponding value.
  • Initialize the variable res to 0, which is used to save the converted integer value.
  • Initialize the variable prev_val to 0, which is used to save the value of the previous character.
  • Use the reversed() function to iterate in reverse over the string s, from the last character to the first character.
  • For each character c, get its corresponding value curr_val.
  • If curr_val is less than prev_val, it means that the value represented by the current character should be subtracted, so subtract it from res.
  • Otherwise, add curr_val to res.
  • Update prev_val to the value of the current character.
  • Returns the final result res, which is a Roman numeral in integer form.

The purpose of this code is to reversely iterate the Roman numeral string s, and accumulate or subtract the corresponding value into res according to the size relationship of adjacent characters, and finally obtain the Roman numeral in integer form. The code utilizes the feature of reverse iteration, which avoids the context of comparing characters each time, thus simplifying logic and code implementation.

The final result is:

insert image description here

Guess you like

Origin blog.csdn.net/wzk4869/article/details/130734003