13. Roman to Integer
Read the full problem statement on LeetCode.
Difficulty: easy Acceptance: 65% Topics: Hash Table, Math, String
View full problem on LeetCode Reading material
Reference solution (spoiler · python)
# Time: O(n)
# Space: O(1)
class Solution(object):
# @return an integer
def romanToInt(self, s):
numeral_map = {"I": 1, "V": 5, "X": 10, "L": 50, "C":100, "D": 500, "M": 1000}
decimal = 0
for i in xrange(len(s)):
if i > 0 and numeral_map[s[i]] > numeral_map[s[i - 1]]:
decimal += numeral_map[s[i]] - 2 * numeral_map[s[i - 1]]
else:
decimal += numeral_map[s[i]]
return decimal
Solution from kamyu104/LeetCode-Solutions · MIT
Similar questions