LeetCode Roman to Integer
LeetCode-solving Roman to Integer
Original question
Converts a roman number to an Arabic number in the range of 1-3999. The following describes the introduction and basic rules of Roman numerals:
The Roman numerals consist of seven Roman letters, I .e., I (1), X (10), C (100), M (1000), V (5), and L (50) and D (500 ). Count method:
If the numbers are the same, the numbers are the same as the numbers obtained by adding these numbers. For example, a small number Ⅲ = 3 is on the right of a large number, the expressed number is equal to the sum of these numbers, for example, a small number (limited to I, X, and C) of item 8 = 8, period = 12 on the left of a large number, the number is equal to the number of a large number.
Note:
The entered roman numerals are compliant with the specifications and do not need to consider errors
Example:
Input: s = "XCIX"
Output: 99
Solutions
According to the rules of the Roman numerals, subtraction is performed only when the first letter is smaller than the current letter. In other cases, you only need to add the numbers corresponding to the Roman letters. If it is found that the first letter is smaller than the current one, it is subtracted from the first letter because it is incorrectly added to the result and the value of the previous letter is subtracted when the current letter is added.
AC Source Code
class Solution(object): def romanToInt(self, s): """ :type s: str :rtype: int """ map = {"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1} result = 0 for i in range(len(s)): if i > 0 and map[s[i]] > map[s[i - 1]]: result -= map[s[i - 1]] result += map[s[i]] - map[s[i - 1]] else: result += map[s[i]] return result# Test casesif __name__ == "__main__": assert Solution().romanToInt("XII") == 12 assert Solution().romanToInt("XXI") == 21 assert Solution().romanToInt("XCIX") == 99