13. Roman to Integer
- Total Accepted: 111025
- Total Submissions: 261201
- Difficulty: Easy
- Contributors: Admin
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Code
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
pre = 0
sum = 0
mapping = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
for ch in s[::-1]:
i = mapping[ch]
if i >= pre:
sum += i
else:
sum -= i
pre = i
return sum
Idea
Fun to know how to read Roman number!
Reference:
https://discuss.leetcode.com/topic/821/my-solution-for-this-question-but-i-don-t-know-is-there-any-easier-way/2 (Answer from vera_qing)