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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-roman-to-integer/
