Converting Roman Numbers into integers (Easy) | LeetCode Practice #3

작성자

카테고리:

← 피드로
DEV Community · 睡觉 · 2026-07-10 개발(SW)

睡觉

睡觉

Posted on Jul 10 • Edited on Jul 12

Roman To Integer

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Given a roman numeral, convert it to an integer.

(I can be placed before V and X to make 4 and 9. X can be placed before L and C to make 40 and 90. C can be placed before D and M to make 400 and 900.)

Python

####Forward Pointer (Runtime: 0ms, Memory: 12.3MB)
    #DECLARE s: STRING
class Solution(object):
    def romanToInt(self, s):
        roman_map = {
            "I": 1, "V": 5, "X": 10, "L": 50,
            "C": 100, "D": 500, "M": 1000
        }
        total = 0
        i = 0
        while i < len(s)-1:
            current = roman_map[s[i]]
            following = roman_map[s[i+1]]
            if current < following:
                total -= current
            else:
                total += current
            i += 1
        total += roman_map[s[-1]]
        return total



####Subtraction Method (Runtime: 5ms, Memory: 12.5MB)
    #DECLARE s: STRING
class Solution(object):
    def romanToInt(self, s):
        roman_map = {
            "I": 1, "V": 5, "X": 10, "L": 50,
            "C": 100, "D": 500, "M": 1000
        }
        last = roman_map[s[0]]
        total = last
        for i in range(1, len(s)):
            current = roman_map[s[i]]
            if current > last:
                total -= 2 * last
            total += current
            last = current
        return total



####Dictionary Matching (Runtime: 8ms, Memory: 12.4MB)
    #DECLARE s: STRING
class Solution(object):
    def romanToInt(self, s):
        roman_map = {
            "I": 1, "IV": 4, "V": 5, "IX": 9,
            "X": 10, "XL": 40, "L": 50, "XC": 90,
            "C": 100, "CD": 400, "D": 500,
            "CM": 900, "M": 1000
        }
        total = 0
        i = 0
        while i < len(s):
            if s[i:(i+2)] in roman_map:
                total += roman_map[s[i:(i+2)]]
                i += 2
            else:
                total += roman_map[s[i]]
                i += 1
        return total

Enter fullscreen mode Exit fullscreen mode

Thoughts

I also tried a Recursion for this one, but in the end, it just didn’t feel appropriate. Recursion only made the code much longer, so I wouldn’t recommend using it. Overall, the question is nice and simple.

원문에서 계속 ↗

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다