简繁EN

LeetCodeNo. 100

[LeetCode with Python] 13. Roman to Integer

Contents

Problem

Problem page: https://leetcode.com/problems/roman-to-integer/
Topics: Math, String
Difficulty: Easy
Similar problems: (M) Integer to Roman

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.


Analysis

Convert a Roman numeral string to the corresponding int.
This problem is a pain in much the same way as Integer to Roman. It's a nightmare if you're not familiar with Roman numerals. The values of the characters in a Roman numeral generally decrease from left to right (two adjacent characters can be equal), so you can just add them up as you go. But if the character on the left has a smaller value than the one on the right, subtract the value of the character on the left. For example, IV is 5-1=4, so CIV is 100-1+5=104.
Space complexity is O(N). Time complexity is O(N).
Watch out for special cases like IV.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
# @return an integer
def romanToInt(self, s):
digits = { "I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000 }
len_s = len(s)
num = 0
for i in range(0, len_s - 1):
cur = digits[s[i]]
next = digits[s[i + 1]]
if cur >= next:
num += cur
else:
num -= cur
num += digits[s[len_s - 1]]
return num

Article link: https://xnerv.wang/en/leetcode-roman-to-integer/